如何在第二个化学点切割数字?



我有一个问题。

我的后端从前端接收号码字符串。

重要的是,我想在第二个化学点上剪数字。

ex1)"2.346"=比;2.34

ex2)"2.3"=比;2.3

要是)"4.246"=比;4.24

ex4)"4.1"=比;4.1

当我用'2.346'或'4.246'尝试这段代码时

let v = '2.346'
v = parseInt(v * 100) / 100
console.log(v)
// v = 2.34

但是当我在2.3或4.1下尝试这段代码时,它会变得很奇怪…

let v = '2.3'
v = parseInt(v * 100) / 100
console.log(v)
// v = 2.29

我的代码有什么问题…?

浮点精度意味着乘以然后除以相同的数字,比如你的parseInt(v * 100) / 100,有时可能会有很长的尾部不重要的数字,这些数字一开始就不存在。

如果我是你,我会使用正则表达式来匹配.后面最多2位数字:

const clean = str => str.match(/d+(?:.d{1,2})?/)[0];
console.log(clean('2.346'));
console.log(clean('2.3'));

function tofixed(str){
return parseInt(str * 1000 / 10) /100
}
console.log(tofixed("2.346"))
console.log(tofixed("2.3"))
console.log(tofixed("4.246"))
console.log(tofixed("4.1"))

最新更新