Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop parseFloat() from stripping zeroes to right of decimal

Tags:

I have a function that I'm using to remove unwanted characters (defined as currency symbols) from strings then return the value as a number. When returning the value, I am making the following call:

return parseFloat(x);

The problem I have is that when x == "0.00" I expect to get 0.00 (a float with two decimals) back. What I get instead is simply 0.

I've also tried the following:

return parseFloat(x).toFixed(2);

and still get simply 0 back. Am I missing something? Any help would be greatly appreciated.

Thank you!!

like image 206
Chris K. Avatar asked Feb 01 '11 22:02

Chris K.


People also ask

What does the parseFloat () method does in Javascript?

The parseFloat() function parses an argument (converting it to a string first if needed) and returns a floating point number.

Does parseFloat return a number?

parseFloat() method parses an argument and returns a floating point number. If a number cannot be parsed from the argument, it returns NaN .

Does parseFloat return a string?

The parseFloat() method parses a value as a string and returns the first number.

Is parseFloat a method?

The parseFloat() method in Float Class is a built in method in Java that returns a new float initialized to the value represented by the specified String, as done by the valueOf method of class Float. Parameters: It accepts a single mandatory parameter s which specifies the string to be parsed.


1 Answers

parseFloat() turns a string into a floating point number. This is a binary value, not a decimal representation, so the concept of the number of zeros to the right of the decimal point doesn't even apply; it all depends on how it is formatted back into a string. Regarding toFixed, I'd suggest converting the floating point number to a Number:

new Number(parseFloat(x)).toFixed(2); 
like image 192
Ted Hopp Avatar answered Oct 12 '22 18:10

Ted Hopp