0

I'm looking to add decimals to the end of my integer. As an example:

15 => 15.00

The problem with methods like toFixed is that it will convert it into a string. I've tried to use parseFloat() and Number() on the string, but it'll convert it back to an integer with no decimals.

Is this possible? If not, can someone explain to me the logic behind why this isn't possible?

EDIT: Welp the intent was to display the number as a number, but from the going consensus, it looks like the way the only way to go about it is to use a string. Found an answer on the why: https://stackoverflow.com/a/17811916/8869701

crackerjack
  • 23
  • 1
  • 7
  • 1
    Formatting makes sense only for output. At such time strings are all you need. – PM 77-1 Aug 11 '18 at 00:10
  • 2
    I really don't know why people ask this question over and over and over. As number, 15.00 is ABSOLUTELY IDENTICAL to 15. There is not a tiny bit of difference. Nada. The question doesn't make any sense whatsoever. – ASDFGerte Aug 11 '18 at 00:21
  • @PM77-1 That makes sense. Is there some explanation in a technical context though? Or is it simply just not built into the JavaScript language because this is purely a cosmetic thing? – crackerjack Aug 11 '18 at 00:23
  • @ASDFGerte it's really only for cosmetic reasons, just trying to understand the concept behind it. – crackerjack Aug 11 '18 at 00:25

2 Answers2

0

When working with numbers 15 and 15.00 are equal. It wouldn't make any sense to use memory to store those trailing or leading zeros. If that information is needed it is usually for displaying purposes. In that case a string is the right choice. In case you need that value again you can parse the string as a number.

NielsNet
  • 818
  • 8
  • 11
  • There are use cases where this is necessary. Like pushing to a backend that validates floats vs integers. So actually would make lots of sense – Brian Leach Feb 04 '22 at 23:47
  • @BrianLeach ... or [trying to verify/match a hash that was generated on data containing currency values with trailing decimal zeros.](https://stackoverflow.com/questions/73420011/how-to-generate-hash-using-node-js-on-data-containing-decimal-trailing-zeros) Any ideas? – romeplow Aug 24 '22 at 20:53
0

The problem you are finding is that all numbers in javascript are floats.

a = 0.1
typeof a # "number"

b = 1
typeof b # number

They are the same.

So there is no real way to convert to from an integer to a float.

This is the reason that all of the parseFloat etc are string methods for reading and writing numbers from strings. Even if you did have floats and integers, specifying the precision of a number only really makes sense when you are displaying it to a user, and for this purpose it will be converted to a string anyway.

Depending on your exact use case you will need to use strings if you want to display with a defined precision.

tmcnicol
  • 576
  • 3
  • 14