Reputation: 1073
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.
Upvotes: 1
Views: 716
Reputation: 2653
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
Upvotes: 0
Reputation: 646
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)
Upvotes: 1
Reputation: 15821
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);
Upvotes: 0
Reputation: 386560
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));
Upvotes: 3