views:

336

answers:

5

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  ->  4.01

Here's how I'm currently doing it:

// chop off unnecessary decimals
if (val.charAt(val.length-1) == '0') { // xx.00
 val = val.substr(0, val.length-1);
}
if (val.charAt(val.length-1) == '0') { // xx.0
 val = val.substr(0, val.length-1);
}
if (val.charAt(val.length-1) == '.') { // xx.
 val = val.substr(0, val.length-1);
}

which works, and has a certain directness to it that I kind of like, but maybe there's a prettier way.

I suppose I could use a loop and run through it three times, but that actually seems like it'll be at least as bulky by the time I conditionalize the if statement. Other than that, any ideas? I imagine there's a regex way to do it, too....

+1  A: 

I believe parseFloat() does this.

parseFloat(4.00) // 4
parseFloat(4.10) // 4.1
parseFloat(4.01) // 4.01
Ólafur Waage
A float may not have enough precision to accurately represent a given decimal value; you should never use them to represent currency.
Andrew Duffy
That's true .
Ólafur Waage
I think they'll be represented correctly as long as you don't do operations on them. And you can't do operations in decimal in JavaScript anyhow (without a decimal library that uses strings or an array of integers internally).
Nosredna
A: 
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.

llimllib
+3  A: 

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(/(\.[1-9]*)0+$/, "$1"); // remove trailing zeros
str.replace(/\.$/, "");             // remove trailing dot
sth
Better to use 0+ instead of 0* so the regex doesn't match if there's no trailing zeros.
llimllib
You're right, 0* with zero 0s matched doesn't do anything useful. But at least it also doesn't do any harm.
sth
A: 

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.

Nosredna
+1  A: 
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);
kennebec