518

I have the following code. I would like to have it such that if price_result equals an integer, let's say 10, then I would like to add two decimal places. So 10 would be 10.00. Or if it equals 10.6 would be 10.60. Not sure how to do this.

price_result = parseFloat(test_var.split('$')[1].slice(0,-1));
Ramratan Gupta
  • 1,056
  • 3
  • 17
  • 39
user357034
  • 10,731
  • 19
  • 58
  • 72

17 Answers17

1121

You can use toFixed() to do that

var twoPlacedFloat = parseFloat(yourString).toFixed(2)
bob esponja
  • 4,093
  • 3
  • 31
  • 29
Mahesh Velaga
  • 21,633
  • 5
  • 37
  • 59
  • 3
    toFixed is quite buggy though. Also, here's a better link than w3schools https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed – gotofritz Aug 12 '12 at 19:14
  • 158
    but toFixed() returns number as string, if you will compare numbers, you need to use parseFloat again. – Pedro Muniz Mar 27 '13 at 12:14
  • 28
    Use `var twoPlacedFloat = + parseFloat(yourString).toFixed(2)` to convert to float – Jose Rui Santos Jul 23 '14 at 10:52
  • 16
    Add parens to get a number instead of string: parseFloat((yourString).toFixed(2)); – pvanallen Nov 19 '14 at 22:02
  • 3
    JavaScript does not have float data type by default. Check this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures It has only number data type. So any attempt to covert number to floating value will actually converts number to string/number representation. So real life float value `2.00` is always string/number in javascript. – Saurin Dashadia Apr 09 '15 at 06:22
  • When use toFixed(2) for more than 16 digits of 9, it will auto round up, you can try with 9999999999999999 and higher amount – Toshihiko Jun 08 '21 at 09:08
  • i had to use something like this: `parseFloat(parseFloat('1234.56789').toFixed(2))` since using `toFixed()` seems to return a string. maybe i am missing something? – edwardsmarkf Aug 19 '21 at 17:32
88

If you need performance (like in games):

Math.round(number * 100) / 100

It's about 100 times as fast as parseFloat(number.toFixed(2))

http://jsperf.com/parsefloat-tofixed-vs-math-round

Rob Boerman
  • 2,148
  • 14
  • 21
  • 9
    With above formula '2.00' returns 2. but I want it to be 2.00. – Saurin Dashadia Apr 09 '15 at 06:08
  • 8
    You can't have it both ways. If you want the output to be a number instead of a string, then you won't get trailing zeros. So you could use the above converted to a string: var twoPlacedFloat = (Math.round(2.002745 * 100) / 100).toFixed(2); – pvanallen Apr 09 '15 at 19:29
  • 9
    WIll the speed increase if I change 100's to 200's? – alashow Aug 13 '17 at 00:32
  • If the number of floating point operations stay the same the speed will be the same, so no – Rob Boerman Aug 13 '17 at 09:24
  • why no simple `number * 1` am I missing something maybe ? – ncubica Nov 11 '17 at 05:34
  • 1
    @ncubica It's about decimal place. If you take 100, then 2 digits after comma, if you take 10, then 1 digit after comma and so on. – alpakyol Nov 28 '17 at 07:04
59

When you use toFixed, it always returns the value as a string. This sometimes complicates the code. To avoid that, you can make an alternative method for Number.

Number.prototype.round = function(p) {
  p = p || 10;
  return parseFloat( this.toFixed(p) );
};

and use:

var n = 22 / 7; // 3.142857142857143
n.round(3); // 3.143

or simply:

(22/7).round(3); // 3.143
kangax
  • 38,898
  • 13
  • 99
  • 135
Vlada
  • 1,653
  • 19
  • 23
  • I wrote a shopping cart program and tried using the toFixed() and the round() methods chained to the parseFloat() method. Neither of these methods worked with the parseFloat(). – Chris22 Nov 06 '13 at 12:49
  • This saved me some to-be headaches. +1 just for that. I had no idea it would turn numbers to strings. – Lukas Jun 20 '14 at 16:39
  • @Lukas Is not, if do parseFloat – Vlada Jul 30 '14 at 17:33
  • 1
    This returns 2 if I apply to '2.00' number – Saurin Dashadia Apr 09 '15 at 06:16
  • This method is for corrections, not for formatting. For example: `0.1 + 0.2 // 0.30000000000000004` so I need correction for that `(0.1+0.2).round() // 0.3` – Vlada Apr 10 '15 at 10:52
21

To return a number, add another layer of parentheses. Keeps it clean.

var twoPlacedFloat = parseFloat((10.02745).toFixed(2));
pvanallen
  • 549
  • 4
  • 10
9

If your objective is to parse, and your input might be a literal, then you'd expect a float and toFixed won't provide that, so here are two simple functions to provide this:

function parseFloat2Decimals(value) {
    return parseFloat(parseFloat(value).toFixed(2));
}

function parseFloat2Decimals(value,decimalPlaces) {
    return parseFloat(parseFloat(value).toFixed(decimalPlaces));
}
Savage
  • 2,296
  • 2
  • 30
  • 40
  • 4
    That not work as espected. `parseFloat(parseFloat('10.5').toFixed(2))` return `10.5` espected `10.50`. Also `parseFloat(parseFloat('10.50').toFixed(2))` return `10.5` – MTK Mar 14 '19 at 17:56
  • It's a float though, so 10.5 is equal to 10.50 – Savage Jul 18 '19 at 08:48
  • 1
    I know that 10.5 == 10.50 but i need to print to client 10.50 not 10.5 – MTK Jul 18 '19 at 11:29
7

ceil from lodash is probably the best

_.ceil("315.9250488",2) 
_.ceil(315.9250488,2) 
_.ceil(undefined,2)
_.ceil(null,2)
_.ceil("",2)

will work also with a number and it's safe

Antonio Terreno
  • 2,835
  • 1
  • 14
  • 9
5

You can use .toFixed() to for float value 2 digits

Exampale

let newValue = parseFloat(9.990000).toFixed(2)

//output
9.99
Rizwan
  • 3,741
  • 2
  • 25
  • 22
  • How can i do the reverse of this? I have 9.99 and want to get 9.990000 – Sofiya rao Sep 02 '22 at 08:00
  • 1
    @Sofiyarao `parseFloat('9.99').toFixed(6)` and you will get 9.990000. `toFixed` determines how many digits are after the decimal – Paul G Nov 08 '22 at 16:51
4
parseFloat(parseFloat(amount).toFixed(2))

You have to parse it twice. The first time is to convert the string to a float, then fix it to two decimals (but the toFixed returns a string), and finally parse it again.

Matt
  • 33,328
  • 25
  • 83
  • 97
2

I have tried this for my case and it'll work fine.

var multiplied_value = parseFloat(given_quantity*given_price).toFixed(3);

Sample output:

9.007

derloopkat
  • 6,232
  • 16
  • 38
  • 45
Habib_95
  • 51
  • 2
1

Please use below function if you don't want to round off.

function ConvertToDecimal(num) {
    num = num.toString(); //If it's not already a String
    num = num.slice(0, (num.indexOf(".")) + 3); //With 3 exposing the hundredths place
   alert('M : ' +  Number(num)); //If you need it back as a Number    
}
Nimesh
  • 3,342
  • 1
  • 28
  • 35
  • Use this as following handles integer values as well function ParseFloat(str, val = 2) { str = str.toString(); if (str.indexOf(".") > 0) { str = str.slice(0, (str.indexOf(".")) + val + 1); } //Following is also an alternative if above does not work //str = str.match(/^-?\d+(?:\.\d{0,2})?/)[0]; return !isNaN(str) ? Number(str) : 0; } – Aditya Jun 24 '21 at 04:22
0

For what its worth: A decimal number, is a decimal number, you either round it to some other value or not. Internally, it will approximate a decimal fraction according to the rule of floating point arthmetic and handling. It stays a decimal number (floating point, in JS a double) internally, no matter how you many digits you want to display it with.

To present it for display, you can choose the precision of the display to whatever you want by string conversion. Presentation is a display issue, not a storage thing.

andora
  • 1,326
  • 1
  • 13
  • 23
0

@sd Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.

Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options

  1. Either use data as a string or
  2. Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5. Number Cannot have trailing zeros after decimal
  • To say there is _no way_ to do it is completely dishonest. Long winded and complicated, sure, but not completely impossible - there are tons of working solutions on this stack alone. – A Friend Mar 26 '21 at 05:58
0

You can store your price as a string

You can use Number(string)

for your calculations.

example

Number("34.50") == 34.5

also

Number("35.65") == 35.65

If you're comfortable with the Number function , you can go with it.

roqkabel
  • 21
  • 4
-2

Try this (see comments in code):

function fixInteger(el) {
    // this is element's value selector, you should use your own
    value = $(el).val();
    if (value == '') {
        value = 0;
    }
    newValue = parseInt(value);
    // if new value is Nan (when input is a string with no integers in it)
    if (isNaN(newValue)) {
        value = 0;
        newValue = parseInt(value);
    }
    // apply new value to element
    $(el).val(newValue);
}

function fixPrice(el) {
    // this is element's value selector, you should use your own
    value = $(el).val();
    if (value == '') {
        value = 0;
    }
    newValue = parseFloat(value.replace(',', '.')).toFixed(2);
    // if new value is Nan (when input is a string with no integers in it)
    if (isNaN(newValue)) {
        value = 0;
        newValue = parseFloat(value).toFixed(2);
    }
    // apply new value to element
    $(el).val(newValue);
}
arghtype
  • 4,376
  • 11
  • 45
  • 60
-2
Solution for FormArray controllers 

Initialize FormArray form Builder

  formInitilize() {
    this.Form = this._formBuilder.group({
      formArray: this._formBuilder.array([this.createForm()])
    });
  }

Create Form

  createForm() {
    return (this.Form = this._formBuilder.group({
      convertodecimal: ['']
    }));
  }

Set Form Values into Form Controller

  setFormvalues() {
    this.Form.setControl('formArray', this._formBuilder.array([]));
    const control = <FormArray>this.resourceBalanceForm.controls['formArray'];
    this.ListArrayValues.forEach((x) => {
      control.push(this.buildForm(x));
    });
  }

  private buildForm(x): FormGroup {
    const bindvalues= this._formBuilder.group({
      convertodecimal: x.ArrayCollection1? parseFloat(x.ArrayCollection1[0].name).toFixed(2) : '' // Option for array collection
// convertodecimal: x.number.toFixed(2)    --- option for two decimal value 
    });

    return bindvalues;
  }
-4

I've got other solution.

You can use round() to do that instead toFixed()

var twoPlacedFloat = parseFloat(yourString).round(2)
Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62
  • 7
    @AustinHenley I tried using round() and it didn't work. That's probably why people are down voting. He may be refering to Math.round() – Nathan Dec 21 '12 at 22:51
  • @Nathan it needs to be used inline, after `parseFloat()` as I've updated the answer by @zsalzbank – Alastair Jun 01 '13 at 12:34
  • 3
    No, it doesn't work. You may try Math.round(parseFloat(yourString), 2); – Augie Gardner Jul 17 '14 at 21:23
  • 1
    Why not downvote an answer which will never work? There's simply no such method as `round()` on numbers in js. The real question is who upvoted this. – meandre Nov 25 '16 at 07:09
-4

The solution that work for me is the following

parseFloat(value)
Jorge Santos Neill
  • 1,635
  • 13
  • 6