-1

I am wondering how to remove decimals in large numbers without it having to round off? My float is: number = 32.223516

The result that I want is 32223516.

When I do this: parseInt(number * 1000000, 10) it gives me 32223515.

And if I use Math.ceil or Math.round, it'll be a problem for cases that would need it to round down.

Is there a cleaner way to do this?

Advance thanks!

  • Never use `parseInt` on things that aren't strings. – T.J. Crowder Dec 21 '20 at 15:55
  • Will you always know that multiplying by 1000000 gives you what should be the integer version of the number? – T.J. Crowder Dec 21 '20 at 15:56
  • The reason `32.223516 * 1000000` doesn't work is that it produces `32223515.999999996` (might have my `9`s count off, but close enough). That's always going to be a problem with floating point, so you need to use rounding of some sort if you do math, or stick to string manipulation. Any reason you can't convert to string and just remove the `.`? (To be clear, there may be such a reason; the string form of a float isn't always what you expect for very large or very small values) – ShadowRanger Dec 21 '20 at 16:01

4 Answers4

1
Number.parseInt(
  yourVariable.toString().replace('.', '')
);
Utku
  • 2,025
  • 22
  • 42
1

Try this:

let number = 32.223516

console.log(parseInt(number.toString().replace('.', '')));
sonEtLumiere
  • 4,461
  • 3
  • 8
  • 35
0

If you know that the number always needs to be multiplied by 1000000 to get what should be the whole number version of it, do that with Math.round:

console.log(Math.round(32.223516 * 1000000));

Otherwise, I'd be tempted to take a round trip through a string:

console.log(+(32.223516).toString().replace(".", ""));

...but you need to beware of scientific notation, see the answers here for how to convert the number to string without scientific notation.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

That is an example of how JavaScript handles all numbers as floating-point numbers.

What can help you in this case is if you convert the number to string form, retain only the desired amount of numbers after the decimal point, which is probably 0 in your case, by using toFixed() method, which would convert and round-off accordingly, like so:

number = 32.223513;
numberToFixed = (num * 1000000).toFixed(0); //argument is amount of numbers to be retained after decimal point