1

I want to round a number in JavaScript but to 2 decimal places but only if necessary.

For example 4.5 to be 4.50 and 3.331 to be 3.331.

I have tried using Math.round(number / 100) * 100 but when number is 4.5 it gives me 4.5 and I want it to be 4.50.

I have tried using .toFixed(2), but when number is 3.331 it will fix it to 3.33.

Any help is much appreciated.

Nafis Islam
  • 1,483
  • 1
  • 14
  • 34
vpp090
  • 603
  • 1
  • 5
  • 9

4 Answers4

3

You could check if the fixed value change and select the kind of formatting.

function format(f) {
    return f === +f.toFixed(2)
        ? f.toFixed(2)
        : f.toString()
}

console.log([4.5, 3.331, 3].map(format));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Using regex check the digits after the dot. if it is less than 2 then use toFixed(2), else do nothing.

function f(n) {
    let diff = Number(n) - Math.floor(Number(n));
    return /\.[0-9]{2,}/.test(diff.toString()) ? n : n.toFixed(2)
}
const nums = [3.331, 2.5, 3].map(f)
console.log(nums)
Janie
  • 638
  • 9
  • 26
0

You can try to apply conditionallu toFixed() method:

const numbers = [4.5, 3.331];
const floated = numbers.map(
  n => {
    const floatLen = n.toString().split('.')[1];
    if(floatLen){
      if(floatLen.toString().length < 2){
        return n.toFixed(2);
      }
    }
  return n;
  }
);
console.log(floated);
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
0

This looks like an String format and not a rounding problem:

var value = 4 + '.';
var [num, dec] = value.split('.');

if (dec.length < 2) {
  dec = (dec + '00').substring(0, 2);
}
console.log(`${num}.${dec}`);

Runnable snippet:

function format(value) {
  var [num, decimal] = (value + '.').split('.');
  
  if (decimal.length < 2) {
    decimal = (decimal + '00').substring(0, 2);
  }

  return `${num}.${decimal}`;  
}

console.log([4, 4.5, 3.331].map(format));

4 -> 4.00

4.5 -> 4.50

3.331 -> 3.331

Phyrum Tea
  • 2,623
  • 1
  • 19
  • 20
  • Not directly related but `num` and `digit` are confusing names. A digit *is* a number. Also, having a digit with any length that's not `1` is impossible. – VLAZ Sep 12 '19 at 11:50
  • I don't see the limit to 1, have to rename the variable names – Phyrum Tea Sep 12 '19 at 11:56
  • A *digit* is a single symbol that creates a number - `1`, `2`, `3`, `4`, `5`, `6`, `7`, `8`, `9`, and `0` are all the digits in decimal. Hex also has `a`, `b`, `c`, `d`, `e`, `f`, for example. A number is composed of one or more digits, so each of these. That's why you have a "two digit number" like `42` or `55`, or "three digit number" - `123`, `216`, `715`, etc. – VLAZ Sep 12 '19 at 12:00
  • I see, you not referring to the variable. – Phyrum Tea Sep 12 '19 at 12:06