-1

What I'm doing is getting user input with

var x = document.getElementById('id'); 

and the output is in whole numbers due to rounding errors, so 1.34 is 134 and I display it with

id.innerHTML = '$'.concat(amount / 100);

It is displaying "$1.32" correctly but I don't want "$1.3" for consistencies sake. So my question is what would be the best way for detecting that "$2.6" for example needs a "0" at the end whereas "$2.53 doesn't? And how to I implement that?

user3473543
  • 131
  • 1
  • 10
  • did you see this? http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript – Ed Manet Sep 03 '14 at 20:17
  • 2
    [MDN: Number.prototype.toFixed()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) – dc5 Sep 03 '14 at 20:19
  • http://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places parseFloat(Math.round(num3 * 100) / 100).toFixed(2); – Jonathan Anctil Sep 03 '14 at 20:19
  • http://stackoverflow.com/questions/1726630/javascript-formatting-number-with-exactly-two-decimals – j08691 Sep 03 '14 at 20:21

4 Answers4

1

Try .toFixed(2) at the end of the number that you want to format

1

Use Number.prototype.toLocaleString:

function formatUSD(value) {
    return value.toLocaleString(['en-US'], {
        style: 'currency', 
        currency: 'USD', 
        minimumFractionDigits: 2, 
        maximumFractionDigits: 2
    });
}
id.textContent = formatUSD(amount / 100);

You probably also want to use a library like big.js instead of floating-point numbers.

  • @sehe ECMAScript 3rd Edition. Implemented in JavaScript 1.5. –  Sep 03 '14 at 20:23
  • Note that not all browsers (versions) support the parameters that `toLocaleString` accepts: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString#Browser_Compatibility – Felix Kling Sep 03 '14 at 20:28
0

try this:

id.innerHTML = '$'.concat((amount / 100).toFixed(2));

It will convert a number to a string with the number of decimal places specified.

Nick Zimmerman
  • 1,471
  • 11
  • 11
  • 1
    @FelixKling Well, I would say because it never hurts to try, but I see your point about a little more explanation being helpful. I edited the post to add an explanation. – Nick Zimmerman Sep 03 '14 at 20:32
  • Thanks that did it! I kept trying (amount.toFixed(2) / 100) but I see how that makes a lot more sense. I'm really new to javascript so the other threads weren't making sense to me. – user3473543 Sep 03 '14 at 20:33
0

Formatting a number with exactly two decimals in JavaScript

use

.toFixed(number of decimal);
Community
  • 1
  • 1
aahhaa
  • 2,240
  • 3
  • 19
  • 30