Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

javascript - Why does parseInt return first letter of a large number?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What parseInt does is:

The parseInt() function parses a string argument and returns an integer of the specified radix (the base in mathematical numeral systems).

If the argument is not a string to begin with, it gets converted into a string.

When a large number is converted into a string, it starts with the most significant digit, followed by a . and eventually e:

console.log(String(53219247129812312132000));
console.log(parseInt(53219247129812312132000))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...