I want to parse a string and I used parseFloat()
, but it removes all the trailing zeroes. How to prevent this - I need to parse the string exactly - if I have 2.5000, I need exactly the same result as a floating-point number - 2.5000.
Asked
Active
Viewed 3.0k times
29
-
6`2.50000` and `2.5` are *the exact same* number. If you want to keep trailing zeroes, you'll have to use a string. – Frédéric Hamidi Jul 22 '14 at 14:02
-
you will have to reformat it to display it. – Daniel A. White Jul 22 '14 at 14:03
1 Answers
28
You can do
parseFloat(2.5).toFixed(4);
If you need exactly the same floating point you may have to figure out the amount
function parseFloatToFixed(string) {
return parseFloat(string).toFixed(string.split('.')[1].length);
}
console.log(parseFloatToFixed('2.54355'));
But i don't really understand why you even need to use parseFloat then? Numbers in javascript do not retain the floating-point count. so you would have to keep them as strings, and calculate against them as floats.
Also don't forget toFixed may have weird rounding issues in different browsers, for example
console.log((0.1).toFixed(20));

Chad Cache
- 9,668
- 3
- 56
- 48
-
1
-
2@Isadora see you have string(a) you convert into float using parseFloat and chad_scira is converting float into string (c). so c=a here so you really don't need this conversion. – Mahi May 09 '17 at 11:54