我有一个字符串123.4567,我想转换为两个小数的数字,我想在Javascript中的1短行中做到这一点。
const x = "123.4567";
// this works but seems way too cumbersome
const y = parseFloat((parseFloat(x)).toFixed(2))
console.log(typeof(y) + " / " + y) //Prints: number / 123.45
// this I expected to work but it doesn't
const z = (parseFloat(x)).toFixed(2)
console.log(typeof(z) + " / " + z) //Prints: string / 123.45
你可以这样做:
const
x = "123.4567"
, y = (0 | (parseFloat(x) *100)) /100 // or (0|parseFloat(x) *100) /100 - see JS Operator precedence
, z = +(+x).toFixed(2) // use + for type cast number
, w = +(0 || x.match(/d*.?d{0,2}/)[0]) // best regex i can do...
;
console.log(`${typeof y} / ${y}`) // number / 123.45
console.log(`${typeof z} / ${z}`) // number / 123.46 the same + 0.01 (rounding)
console.log(`${typeof w} / ${w}`) // number / 123.45
Nb:( 0 | number )
返回任意浮点数的整数部分(|
=二进制或运算符)