I\'ve got a currency input and need to return only significant digits. The input always has two decimal places, so:
4.00 -> 4
4.10 -> 4.1
4.01 ->
String(4) // "4"
String(4.1) // "4.1"
String(4.10) // "4.1"
String(4.01) // "4.01"
parseFloat works, but you've got to cast it back to a string.
string to string: parseFloat(value).toFixed(2);
string to number: +(parseFloat(value).toFixed(2))
number to number: Math.round(value*100)/100;
number to string: (Math.round(value*100)/100).toFixed(2);
So you're starting with a string and you want a string result, is that right?
val = "" + parseFloat(val);
That should work. The more terse
val = "" + +val;
or
val = +val + "";
would work as well, but that form is too hard to understand.
How do these work? They convert the string to a number then back to a string. You may not want to use these, but knowing how the JavaScript conversions work will help you debug whatever you do come up with.
I think this is what you want
v = 33.404034
v.toFixed(2) # v -> 33.40
parseFloat(v.toFixed(2)) # 33.4
and you have
v = 33.00704034
v.toFixed(2) # v -> 33.01
parseFloat(v.toFixed(2)) # 33.01
v = 33.00304034
v.toFixed(2) # v -> 33.00
parseFloat(v.toFixed(2)) # 33
I am trying to find a solution like that right now. This is how I got here.
I used Number() function for my application, but looks like it's working the same as parseFloat()
http://jsfiddle.net/4WN5y/
I remove and commas before checking the number.
var valueAsNumber = Number( val.replace(/\,/g,'') );
Your code also chops off zeros in numbers like "1000". A better variant would be to only chop of zeros that are after a decimal point. The basic replacement with regular expressions would look like this:
str.replace(/(\.[0-9]*?)0+$/, "$1"); // remove trailing zeros
str.replace(/\.$/, ""); // remove trailing dot