我想在javascript中从数字中删除小数:这样的东西:
12 => 12
12.00 => 1200
12.12 => 1212
12.12.12 => error: please enter valid number.
Run Code Online (Sandbox Code Playgroud)
我不能用Math.round(number)
.因为,它会给我不同的结果.我怎样才能做到这一点?谢谢.
处理前三个示例的最简单方法是:
function removeDecimal(num) {
return parseInt(num.toString().replace(".", ""), 10);
}
Run Code Online (Sandbox Code Playgroud)
这假设参数已经是一个数字,在这种情况下你的第二个和第四个例子是不可能的.
如果不是这样的话,你需要计算字符串中的点数,使用类似的东西(从这个问题中获取技巧):
(str.match(/\./g) || []).length
Run Code Online (Sandbox Code Playgroud)
结合两者并投掷,你可以:
function removeDecimal(num) {
if ((num.toString().match(/\./g) || []).length > 1) throw new Error("Too many periods!");
return parseInt(num.toString().replace(".", ""), 10);
}
Run Code Online (Sandbox Code Playgroud)
这适用于大多数数字,但可能会遇到特别大或精确值的舍入误差(例如,removeDecimal("1398080348.12341234")
将返回139808034812341230
).
如果您知道输入将始终是一个数字并且您想要变得非常棘手,您还可以执行以下操作:
function removeDecimal(num) {
var numStr = num.toString();
if (numStr.indexOf(".") === -1) return num;
return num * Math.pow(10, numStr.length - numStr.indexOf(".") - 1);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
251 次 |
最近记录: |