1

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?

codemonkey
  • 7,325
  • 5
  • 22
  • 36

1 Answers1

1

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))

Since 5 is the starting "integer" part of the string before the dot, that's the result. (The engine stops trying to parse the string once it encounters the dot, since it considers characters past that to not be part of the integer part of the number.)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • So what you're saying is the reason this works fine `parseInt("532192471298123123987897987")` is because that specific string is being fed to `parseInt`. And the reason this works weird `parseInt("53219247129812312311" * 100)` is because after multiplication, this `5.321924712981231e+21` is being fed into `parseInt`. Right? – codemonkey Jan 24 '21 at 07:22
  • Yeah - a bit more precisely, the *string* containing the exponential notation is being used by `parseInt`, `'5.321924712981231e+21'` – CertainPerformance Jan 24 '21 at 07:24