-1

When I use p=10000 ,r=15 and n=60 in the below ...

var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100).toFixed(2));

x = 237.9 instead of 237.90.

If the combo of p, r and n result in a number that is not $xx.x", then the code snippet works fine ...ie. formats to 2 decimal places.

But why is it displaying 237.9 instead of 237.90?

James Ling
  • 11
  • 1
  • 2
  • Hi Barmar -- can you please refer me to the responses to the identical question? Thanks – James Ling Dec 30 '16 at 02:12
  • Click on the link. – Barmar Dec 30 '16 at 02:13
  • @Barmar The problem here isn't wrong usage of `toFixed` (as N [does indeed mean exactly N decimal digits](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed)), it's that the result is converted back into a float. – Frxstrem Dec 30 '16 at 02:17
  • @Frxstrem I've reopened the question, you should turn that into an answer. – Barmar Dec 30 '16 at 02:20

2 Answers2

1

When you call number.toFixed(2), you do indeed get a string representation of the number with two decimal digits:

var number = 237.9;
number.toFixed(2);             // '237.90'

However, when you then use parseFloat on this, you convert it back to a number again; since a number does not contain information about the number of zeros to display, the last zero is dropped as it is printed:

parseFloat(number.toFixed(2)); // 237.9

To avoid this, simply don't convert your string back into a float, but use it as a string.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119
0
var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);

p=10000,r=15, n=60;

var x = parseFloat((Math.round(r/12/100*p/(1-Math.pow(1+ +(r/12/100),-n))*100)/100)).toFixed(2);

console.log(x)

Add toFixed after all operations. You need string, basically...

sinisake
  • 11,240
  • 2
  • 19
  • 27