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....
I believe parseFloat() does this.
parseFloat(4.00) // 4
parseFloat(4.10) // 4.1
parseFloat(4.01) // 4.01
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With