0

I have a series of numbers. For example:

3, 3.4567, 4.5, 5.72, 6.12345

How can I show original numbers if they are integers or they have no more than 3 digits after the decimal point and show max 3 digits after the decimal point if there are more than 3? Here is what I want:

3, 3.456, 4.5, 5.72, 6.123

I used toFixed(), but it makes each number come with 3 digits after the decimal point.

Is there any Javascript method to use to achieve what I want?

--------- update -----------

I used this from the pointer:

Math.round(original*1000)/1000

from the old post. It seems working.

curious1
  • 14,155
  • 37
  • 130
  • 231
  • 1
    The answer from the question I linked applies here as well (slightly modified): val = (Math.floor(val * 1000) / 1000).toString() – Psi Feb 27 '17 at 02:32
  • 1
    See the second answer on the duplicate, answers your question. – Andrew Li Feb 27 '17 at 02:35

3 Answers3

4

You can use Number.prototype.toPrecision() to round to nearest 3 digits after decimal point, then parseFloat() the result:

var num = 6.12345;
var precise = num.toPrecision(4); //"6.123"
var result = parseFloat(precise); //6.123

var num = 4.5;
var precise = num.toPrecision(4); //"4.500"
var result = parseFloat(precise); //4.5

If these numbers are in an array, you can create a function customPrecision to map:

function customPrecision(num) {
  return parseFloat(num.toPrecision(4));
}

var nums = [3, 3.4567, 4.5, 5.72, 6.12345];
var preciseNums = nums.map(customPrecision); //[3, 3.457, 4.5, 5.72, 6.123]
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
2

Just cast the fixed strings back into numbers using the unary + operator before printing them:

var floats = [3, 3.4567, 4.5, 5.72, 6.12345]

function toMax3Decimals (x) {
  return +x.toFixed(3)
}

console.log(floats.map(toMax3Decimals))
gyre
  • 16,369
  • 3
  • 37
  • 47
  • 3
    You beat me by a few seconds. In case the OP didn't know, converting to a Number gets rid of the trailing zeros. – Andrew Li Feb 27 '17 at 02:34
1

Not sure this is the best way, but it works

Math.floor(3.4567*1000)/1000
Math.floor(6.12345*1000)/1000
Aligma
  • 562
  • 5
  • 29