-1

see, i wanted to display a decimal number correctly because if the number has the decimal .10, .20, .30, etc.., it would only show up as 0.1 and not 0.10

i've already checked the other questions for this such as this, but even the top answer didn't solve my problem as it still only showed 1 digit. here's what i tried so far, but seemed to not work:

if(coins%0.10===0)
{
   coins=coins+'0';
}
else
{
   coins=coins;
}

EDIT: Okay, now i feel reaaaally dumb. I tried .toFixed(2) before i asked this question, but it previously showed up as 0.1 so i tried something else which is the one above. And then I tried .toFixed(2) again when i saw the answers and it now displays correctly. Idk what happened to be honest. And no, I did not mistype the function or anything or missed a semi-colon.

Thank you!

4 Answers4

0

var arr = [0.1,0.2,0.3];
for(var i=0;i<arr.length;i++){
  console.log(arr[i].toFixed(2))
}

Use above.

Ullas Hunka
  • 2,119
  • 1
  • 15
  • 28
0

var n = .10;
var fixedDecimal = n.toFixed(2);

console.log(fixedDecimal)
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46
0

Please make use of toFixed()

Here are few examples from MDN

var numObj = 12345.6789;

numObj.toFixed();       // Returns '12346': note rounding, no fractional part
numObj.toFixed(1);      // Returns '12345.7': note rounding
numObj.toFixed(6);      // Returns '12345.678900': note added zeros
(1.23e+20).toFixed(2);  // Returns '123000000000000000000.00'
(1.23e-10).toFixed(2);  // Returns '0.00'
2.34.toFixed(1);        // Returns '2.3'
2.35.toFixed(1);        // Returns '2.4'. Note it rounds up
2.55.toFixed(1);        // Returns '2.5'. Note it rounds down - see warning above
-2.34.toFixed(1);       // Returns -2.3 (due to operator precedence, negative number literals don't return a string...)
(-2.34).toFixed(1);     // Returns '-2.3' (...unless you use parentheses)
Thiru
  • 96
  • 8
0

Is this what you meant?

var coins = "0.20";

document.getElementById('coins1').innerHTML = Number(coins).toFixed(2);
<span id="coins1"></span>
  • List item
Rekiyan Seto
  • 33
  • 1
  • 5