I would like to format my numbers to always display 2 decimal places, rounding where applicable.
Examples:
number display
------ -------
1
function number_format(string,decimals=2,decimal=',',thousands='.',pre='R$ ',pos=' Reais'){
var numbers = string.toString().match(/\d+/g).join([]);
numbers = numbers.padStart(decimals+1, "0");
var splitNumbers = numbers.split("").reverse();
var mask = '';
splitNumbers.forEach(function(d,i){
if (i == decimals) { mask = decimal + mask; }
if (i>(decimals+1) && ((i-2)%(decimals+1))==0) { mask = thousands + mask; }
mask = d + mask;
});
return pre + mask + pos;
}
var element = document.getElementById("format");
var money= number_format("10987654321",2,',','.');
element.innerHTML = money;
#format{
display:inline-block;
padding:10px;
border:1px solid #ffffd;
background:#f5f5f5;
}
<div id='format'>Test 123456789</div>
var num = new Number(14.12);
console.log(num.toPrecision(2));//outputs 14
console.log(num.toPrecision(3));//outputs 14.1
console.log(num.toPrecision(4));//outputs 14.12
console.log(num.toPrecision(5));//outputs 14.120
Here's also a generic function that can format to any number of decimal places:
function numberFormat(val, decimalPlaces) {
var multiplier = Math.pow(10, decimalPlaces);
return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}
This answer will fail if value = 1.005
.
As a better solution, the rounding problem can be avoided by using numbers represented in exponential notation:
Number(Math.round(1.005+'e2')+'e-2'); // 1.01
Cleaner code as suggested by @Kon, and the original author:
Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces)
You may add toFixed()
at the end to retain the decimal point e.g: 1.00
but note that it will return as string.
Number(Math.round(parseFloat(value + 'e' + decimalPlaces)) + 'e-' + decimalPlaces).toFixed(decimalPlaces)
Credit: Rounding Decimals in JavaScript
Just run into this one of longest thread, below is my solution:
parseFloat(Math.round((parseFloat(num * 100)).toFixed(2)) / 100 ).toFixed(2)
Let me know if anyone can poke a hole
Are you looking for floor?
var num = 1.42482;
var num2 = 1;
var fnum = Math.floor(num).toFixed(2);
var fnum2 = Math.floor(num2).toFixed(2);
alert(fnum + " and " + fnum2); //both values will be 1.00