Why is Javascript not showing the decimal home number?

Asked

Viewed 128 times

8

The example below normally sample the two zero:

console.log(100);

But when placing a decimal place or more it does not show:

console.log(100.000);

  • 4

    Decimals only with 0 is ignored. You would have to use 100.000.toFixed(3). Only that the .toFixed() converts the number into a string.

  • @Sam, thank you so much!

1 answer

8


Because you didn’t show it. A common mistake that people make is to think that what you’re seeing are numbers. Nothing you enter or order out of an application for a human to manipulate are numbers in fact.

There is an ambiguity of what we live with in mathematics (we write on paper when we calculate something a text that represents numbers and spend a lifetime thinking that it is a number, but it is not, there is only the representation of the number)but in computer it is necessary to be more precise in the definitions.

The number exists by itself, you do not see it, it is an abstraction. To see the number you need to find the textual representation of it, which is something more concrete. And you’re talking about this representation.

When you print something that is numerical, the JS library internally converts a number to a text and this is what you see. The standard form of the language is to do this in the simplest format you can. Then the number we know as 100 will be printed as the text "100", no matter how you typed it into the code, it’s only the number 100, and when you type in the code you’re putting the number, not what you’re seeing there, the compiler converts this text into number.

You remember the math? Zeros on the left before the decimal part and zeros on the right at the decimal part have no relevance, so 100,000 does not exist as a number, there is only 100. There is the textual representation "100,000". And when it is printed, it only prints what is actually 100.

If you want to force a specific format for the textual representation of the number then you have to say it in the code when printing explicitly as you want. It may be so:

console.log(100..toFixed(3));

Note that you don’t even need to use the number with the boxes because as already said these zeros after the comma have no relevance.

It is important to realize that this function toFixed() returns a text and not a number, so you see the decimal places placed.

I had to use .., the first point is to finalize the number and make it unambiguous that then comes a point of the method to be applied. Could have written so:

console.log(100.0.toFixed(3));

Or:

console.log((100).toFixed(3));

I put in the Github for future reference.

If it was a variable it wouldn’t have this problem because it doesn’t get ambiguous, it’s just a JS syntax question.

  • thanks very well explained!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.