Javascript: Formatting a Rounded Number to N Decimals

Javascript: formatting a rounded number to N decimals

That's not a rounding ploblem, that is a display problem. A number doesn't contain information about significant digits; the value 2 is the same as 2.0000000000000. It's when you turn the rounded value into a string that you have make it display a certain number of digits.

You could just add zeroes after the number, something like:

var s = number.toString();
if (s.indexOf('.') == -1) s += '.';
while (s.length < s.indexOf('.') + 4) s += '0';

(Note that this assumes that the regional settings of the client uses period as decimal separator, the code needs some more work to function for other settings.)

Formatting a number with exactly two decimals in JavaScript

To format a number using fixed-point notation, you can simply use the toFixed method:

(10.8).toFixed(2); // "10.80"

var num = 2.4;
alert(num.toFixed(2)); // "2.40"

Note that toFixed() returns a string.

IMPORTANT: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.

For instance:

2.005.toFixed(2) === "2.00"

UPDATE:

Nowadays, you can use the Intl.NumberFormat constructor. It's part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.

const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});

console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"

How do you round to 1 decimal place in Javascript?

Math.round(num * 10) / 10 works, here is an example...

var number = 12.3456789
var rounded = Math.round(number * 10) / 10
// rounded is 12.3

if you want it to have one decimal place, even when that would be a 0, then add...

var fixed = rounded.toFixed(1)
// fixed is always to 1 d.p.
// NOTE: .toFixed() returns a string!

// To convert back to number format
parseFloat(number.toFixed(2))
// 12.34
// but that will not retain any trailing zeros

// So, just make sure it is the last step before output,
// and use a number format during calculations!

EDIT: Add round with precision function...

Using this principle, for reference, here is a handy little round function that takes precision...

function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}

... usage ...

round(12345.6789, 2) // 12345.68
round(12345.6789, 1) // 12345.7

... defaults to round to nearest whole number (precision 0) ...

round(12345.6789) // 12346

... and can be used to round to nearest 10 or 100 etc...

round(12345.6789, -1) // 12350
round(12345.6789, -2) // 12300

... and correct handling of negative numbers ...

round(-123.45, 1) // -123.4
round(123.45, 1) // 123.5

... and can be combined with toFixed to format consistently as string ...

round(456.7, 2).toFixed(2) // "456.70"

How to round to at most 2 decimal places, if necessary

Use Math.round() :

Math.round(num * 100) / 100

Or to be more specific and to ensure things like 1.005 round correctly, use Number.EPSILON :

Math.round((num + Number.EPSILON) * 100) / 100

JavaScript: Round to a number of decimal places, but strip extra zeros

>>> parseFloat(0.9999999.toFixed(4));
1
>>> parseFloat(0.0009999999.toFixed(4));
0.001
>>> parseFloat(0.0000009999999.toFixed(4));
0

Format number to always show 2 decimal places

(Math.round(num * 100) / 100).toFixed(2);

Live Demo

var num1 = "1";document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);
var num2 = "1.341";document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);
var num3 = "1.345";document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
span {    border: 1px solid #000;    margin: 5px;    padding: 5px;}
<span id="num1"></span><span id="num2"></span><span id="num3"></span>

Rounding number to two decimal places

As Jordan said. When JavaScript displays the number it'll drop the 0. I'd just store the value as is and when you display it, run it through the .toFixed(2) so that it displays properly. Or even better, find a currency formatter since that seems to be what you're looking to display and use that on the view side.

Here's a nice currency formating script.

Number.prototype.formatMoney = function(c, d='.', t=','){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

Then you can use it an object oriented fashion with this code:

price.formatMoney(2);

Or if you want to specify the thousands and decimal separators for Europe.

price.formatMoney(2, ',', '.');

JavaScript math, round to two decimal places

NOTE - See Edit 4 if 3 digit precision is important

var discount = (price / listprice).toFixed(2);

toFixed will round up or down for you depending on the values beyond 2 decimals.

Example: http://jsfiddle.net/calder12/tv9HY/

Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Edit - As mentioned by others this converts the result to a string. To avoid this:

var discount = +((price / listprice).toFixed(2));

Edit 2- As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. If accuracy to this degree is important I've found this answer: https://stackoverflow.com/a/32605063/1726511 Which seems to work well with all the tests I've tried.

There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices.

Edit 3 - Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. Geez so many reworks!

var discount = roundTo((price / listprice), 2);

function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}

var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
var test =(Math.round(n) / multiplicator);
return +(test.toFixed(digits));
}

See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/

Edit 4 - You guys are killing me. Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result.

function roundTo(n, digits) {
var negative = false;
if (digits === undefined) {
digits = 0;
}
if (n < 0) {
negative = true;
n = n * -1;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
n = (Math.round(n) / multiplicator).toFixed(digits);
if (negative) {
n = (n * -1).toFixed(digits);
}
return n;
}

Fiddle: https://jsfiddle.net/3Lbhfy5s/79/



Related Topics



Leave a reply



Submit