chop unused decimals with javascript

眉间皱痕 提交于 2019-12-04 17:22:10

问题


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:


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



回答2:


I believe parseFloat() does this.

parseFloat(4.00) // 4
parseFloat(4.10) // 4.1
parseFloat(4.01) // 4.01



回答3:


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



回答4:


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



回答5:


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.




回答6:


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.




回答7:


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


来源:https://stackoverflow.com/questions/1015402/chop-unused-decimals-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!