1

I have a number generated as a finite decimal:

var x = k * Math.pow(10,p)

with k and p integers. Is there a simple way to convert it to an exact string representation?

If I use implict string conversion I get ugly results:

""+ 7*Math.pow(10,-1)

gives

"0.7000000000000001"

I tried using .toFixed and .toPrecision but it is very difficult to find the correct precision to use depending on k and p. Is there a way to get the good old "%g" formatting of C language? Maybe I should resort to an external library?

Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64

2 Answers2

1

One can use math.format from math.js library:

math.format(7 * Math.pow(10, -1), {precision: 14});

gives

"0.7"
Emanuele Paolini
  • 9,912
  • 3
  • 38
  • 64
0

You can create your own floor function like this, with option accuracy

  function fixRound(number, accuracy) {

      return ""+Math.floor(number * (accuracy || 1)) / accuracy || 1;

  }

  let num = 7 * Math.pow(10, -1);

  console.log(fixRound(num, 1000))
Vadim Hulevich
  • 1,803
  • 8
  • 17
  • 1
    The arithmetic in `fixRound` cannot work because .7 is not exactly representable in the JavaScript `Number` format, so no calculating can ever round a number to exactly .7. It can get close enough that the default formatting will print “.7”, so this kludge may work for some purposes. But `fixRound` is also subject to rounding errors in the multiply and the divide. The request OP makes ought to be addressed by using formatting features (which internally handle the conversion to decimal with calculations that avoid additional rounding errors), not by attempting to fudge the arithmetic. – Eric Postpischil Apr 16 '19 at 19:36