I need to round a value with 2 decimal places that I receive from a web service. To do this i use this methods toFixed and parseFloat because I need the final value in a float. However when I have this value "5.5000000" he shows me the value with only one decimal place "5.5"...
I did in that way:
var num = 5.5000000;
var n = num.toFixed(2);
var numFinal = parseFloat(n);
I need to round a value with 2 decimal places that I receive from a web service. To do this i use this methods toFixed and parseFloat because I need the final value in a float. However when I have this value "5.5000000" he shows me the value with only one decimal place "5.5"...
I did in that way:
var num = 5.5000000;
var n = num.toFixed(2);
var numFinal = parseFloat(n);
Share
Improve this question
asked Jun 17, 2016 at 11:28
sampaioPTsampaioPT
1151 gold badge2 silver badges10 bronze badges
8
-
If you have a number and want a string you don't need
parseFloat()
because that function does the exact opposite (convert from string to number). – Álvaro González Commented Jun 17, 2016 at 11:40 - but the method toFixed returns a string and i want a float – sampaioPT Commented Jun 17, 2016 at 13:55
-
"5.5000000"
is just how the float happens to be displayed when you print it. There's no direct translation between the internal base 2 representation of a floating point number and decimals in a given base 10 representation. – Álvaro González Commented Jun 17, 2016 at 14:53 - 1 @sampaioPT, Refer stackoverflow./a/2283670/1746830 – Rayon Commented Jun 18, 2016 at 4:48
- 1 Thanks for reply @ÁlvaroGonzález! Now i understand! (I owe you one beer ;) ) – sampaioPT Commented Jun 20, 2016 at 15:53
3 Answers
Reset to default 8You have to call toFixed
after parseFloat
:
parseFloat(yourString).toFixed(2)
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
- Either use data as a string or
- Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5. Number Cannot have trailing zeros after decimal
You can do something like this
/**
* Convert the value to the Number with the precision.
* @param {Number} value value to be converted
* @param {Number} [precision=0] number of decimal places
* @returns {Number} converted number.
*/
function toNumber (value, precision) {
precision = precision || 0;
if (precision === 0) {
return value * 1;
} else {
return Number((value * 1).toFixed(precision));
}
}