The question sprang up from reading the answers to this recent post.
The OP simply wants to know how to cut off a string at the second decimal point: e.g. '2.346' => 2.34
One of the users provided this answer:
function tofixed(str){
return parseInt(str * 1000 / 10) /100
}
I tested it with a very large number and got this result:
console.log(tofixed('53219247129812312132.453'))
//Result: 0.05
I got curios and started digging. The quirk seems to lie with parseInt
, because I can easily run this:
console.log(53219247129812312132 * 1000 / 10)
OR
console.log("53219247129812312132" * 1000 / 10)
And get the proper result. But why do I get 5
when I run:
console.log(parseInt("53219247129812312132" * 1000))
It seems to always return the first character of the string. I thought perhaps the number is too large for parseInt to parse, but why, then can I parse this without any issues:
console.log(parseInt("5321924712981231213212323232323"))
That multiplication seems to throw parseInt
for a loop when combined with a large number. Can someone explain this behavior to me?
question from:
https://stackoverflow.com/questions/65867975/why-does-parseint-return-first-letter-of-a-large-number 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…