Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  162] [ 6]  / answers: 1 / hits: 28357  / 10 Years ago, tue, july 22, 2014, 12:00:00

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.


More From » parsing

 Answers
26

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));

[#70102] Monday, July 21, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
arthur

Total Points: 729
Total Questions: 107
Total Answers: 109

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;