1

I need to represent a number with fixed amount of digits in total in Javascript (using NodeJs). In other words, fractional part is different depending on the overall value.

So 4.22525252525 becomes 4.22525, but 1242.122412512 becomes 1242.12, 124.2352352 becomes 124.235.

How can I achieve this?

onkami
  • 8,791
  • 17
  • 90
  • 176

1 Answers1

1

Use Number.prototype.toPrecision():

console.log(
  (4.22525252525).toPrecision(6), // 4.22525
  (1242.122412512).toPrecision(6), // 1242.12
  (124.2352352).toPrecision(6) // 124.235
)

This has the added bonus that it will convert the number to exponential notation if the number of digits before the decimal point is bigger than the number of digits specified.

D. Pardal
  • 6,173
  • 1
  • 17
  • 37