1

Can you guys explain why string conversion of 65.00 returns 65 instead of 65.00?

  var dec_1 = 65.01;
  var dec_2 = 65.00;
  var n1 = String(dec_1);  // returns 65.01
  var n2 = String(dec_2);  // returns 65
1
  • I'm sure there's a dupetarget for the sort-of-implied "how" part of this question, but I've never seen the "why" part of it before. Commented Aug 21, 2020 at 10:37

2 Answers 2

4

Because that's how Number.prototype.toString is specified to work. It only includes as many places after the decimal as it needs to differentiate the number from another representable number.¹

If you want a fixed number of decimal places, use toFixed:

var dec_1 = 65.01;
var dec_2 = 65.00;
var n1 = dec_1.toFixed(2); // "65.01"
var n2 = dec_2.toFixed(2); // "65.00"
console.log(n1);
console.log(n2);


¹ This is true even if the actual number value, if printed in full, would have had more non-zero digits on it. Full details in the specification, it's actually quite an involved process which is the subject of significant academic research.

For example, consider the number 1.1:

console.log(String(1.1)); // "1.1"

Simple enough, right? Except that 1.1 can't be represented exactly in the IEEE-754 double-precision floating point number type that JavaScript uses. When you use 1.1 in your code, the number value that creates is ever so slightly higher than 1.1:

console.log((1.1).toFixed(52)); // "1.1000000000000000888178419700125232338905334472656250"

The reason the default toString doesn't include those digits is that they aren't important; both 1.1 and 1.1000000000000000888178419700125232338905334472656250 end up being the same bit pattern in the number. So those extra digits aren't necessary to differentiate the number from the next representable number. So they're left off.

You can see that here:

console.log(1.1 === 1.1000000000000000888178419700125232338905334472656250); // true

Sign up to request clarification or add additional context in comments.

Comments

0

Use toFixed:

var n2 = dec_2.toFixed(2)

2 Comments

The OP was asking how to add 2 decimal digits to a whole number in the output. The toFixed() method is a built-in method of numeric data types that converts the number into a string with provided dumber of digits after the decimal point (see [link] (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… using this method will display the number 65 as "65.00" and not as "65" - which was the original question.
Thanks, it would be great if you also included the explanation in the answer itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.