-2

My program (which uses Math.round) does not display the second decimal when the result is round (ex: 1.10, 1.30) while yes when the result is not round (ex: 1.24, 2.47). How to change this?

function calcAmount2() {
  var userAmount2 = document.getElementById("amount2").value;
  if (userAmount2 = Number(amount2.value)) {
    document.getElementById("marginAmount2").textContent =
      Math.round(userAmount2 * 3) / 100 + "€";
  }
}

(expected)1.10, 1.30 instead of (actually) 1.1 1.3

Eddie
  • 26,593
  • 6
  • 36
  • 58
  • JavaScript does not have significant places. You can use toFixed()... too lazy to find the dupe – epascarello Apr 29 '19 at 14:14
  • 2
    Possible duplicate of [Formatting a number with exactly two decimals in JavaScript](https://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript) – Dexygen Apr 29 '19 at 14:15

3 Answers3

4

(Math.round(userAmount2 * 3) / 100).toFixed(2) + "€";

toFixed sets the number to always have 2 decimals.

JensW
  • 442
  • 2
  • 12
2

I believe this is a duplicate of Format number to always show 2 decimal places

You want to use .toFixed(2) it seems, though be aware the result will be a String.

pmiller3
  • 161
  • 5
1

I am not sure how specific your answer has to be, but I would recommend you to use this instead:

const res = Number(Math.round(userAmount2 +'e2')+'e-2');

This is because toFixed has the rounding problem for some values such as 21.005.

Let me prove it to you over here:

    
console.log(Number(Math.round(20.005 +'e2')+'e-2'));
console.log(20.005.toFixed(2));
wentjun
  • 40,384
  • 10
  • 95
  • 107
  • You're right, Gojun! There is problem of rounded value with 3 decimals. But, we can see as cool with euro, sometimes only. So, i willtest youre solution but i'm not understand this code. what is signification of "e2" and e-2"? I'm a beginner in javascript and i prefere when i understand what i doThanks a lot. – Philippe Delestan Apr 29 '19 at 18:27
  • @PhilippeDelestan ah, I must have missed out that part on `e`. e in scientific/numeric notation refers to the number, times 10 to the power of the suffix! Therefore, `e2` means x10^2, and `e-2` means x10^-2. – wentjun Apr 29 '19 at 19:05
  • I am essentially 'scaling' the number by two figures (x100) across the decimal point, rounding the value, followed by multiplying it back by (10^-2), in order to avoid all that floating point issues. – wentjun Apr 29 '19 at 19:10
  • Yes, i understand very well. Thank you, Gojun. – Philippe Delestan Apr 29 '19 at 20:10