0

I've tried basically everything here: JavaScript math, round to two decimal places

Not only do I want to reduce it to two decimals, but if it's less I need to add a zero. I'm using .1 in my examples below.

var base = .1;  //desired result is 0.10
var total;

// the x100/100 method
total = (base * 100) / 100;
console.log(total);  //outputs 0.1

// the .toFixed method
total = (base).toFixed(2);
console.log(total + " (" + typeof total + ")"); //looks right, but it's a string

// unary +()
total = +((base).toFixed(2));
console.log(total); //outputs .1
  • because you convert it to a number.... numbers do not have significant digits. – epascarello Feb 28 '18 at 21:09
  • It only makes sense to do that as a string. Numbers are binary floating-point values. – Pointy Feb 28 '18 at 21:09
  • So you're saying it's impossible to output a trailing zero as a number? –  Feb 28 '18 at 21:09
  • Thanks @Pointy, your comment was more clear :) –  Feb 28 '18 at 21:09
  • Yes. A number like `.1` cannot be represented exactly in binary floating point. – Pointy Feb 28 '18 at 21:10
  • Makes sense, can you post as an answer? –  Feb 28 '18 at 21:10
  • Well [this question](/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary) is *almost* a good duplicate, because the best answer is pretty clear and extensive. – Pointy Feb 28 '18 at 21:14
  • No, that clearly says "At most" and mine specifically mentions padding zeros (which would be *at least*) –  Feb 28 '18 at 21:15

0 Answers0