使用javascript切掉未使用的小数 [英] chop unused decimals with javascript

查看:75
本文介绍了使用javascript切掉未使用的小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有货币输入,只需返回有效数字。输入始终有两个小数位,因此:

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

以下是我目前的做法:

// 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.

我想我可以使用一个循环并运行它三次,但实际上,当我将if语句条件化时,它至少会变得笨重。除此之外,还有什么想法吗?我想也有一个正则表达式的方法呢....

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

推荐答案

你的代码也会删除数字中的零,如 1000\" 。一个更好的变体是只能在小数点后面切出零。正则表达式的基本替换如下所示:

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

这篇关于使用javascript切掉未使用的小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆