Multiplication gives approximate results - javascript

Hmm I have an issue with roundings on the client side which is then validated in the backend and the validation is failing due to this issue. Here is the previous question Javascript and C# rounding hell
So what I am doing is:
On client side:
I have 2 numbers: 50 and 2.3659
I multiply them: 50 * 2.3659 //118.29499999999999
Round to 2 decimal places: kendo.toString(50 * 2.3659, 'n2') //118.29
In backend(C#):
I am doing the same: 50 and 2.3659
I multiply them: 50 * 2.3659 //118.2950
Round to 2 decimal places: Math.Round(50 * 2.3659, 2) //118.30
And validation is failing. Can I do something on the client side?

Can you try parseFloat and toFixed functions as follows :
var mulVal = parseFloat(50) * parseFloat(2.3659);
var ans = mulVal.toFixed(2);
console.log(ans);

Javascript Arithmetic is not always accurate, and such erroneous answers are not unusual. I would suggest that you use Math.Round() or var.toFixed(1) for this scenario.
Using Math.Round:
var value = parseFloat(50) * parseFloat(2.3659);
var rounded = Math.round(value);
console.log(rounded);
Prints 118 to the console.
Using toFixed() method:
var value = parseFloat(50) * parseFloat(2.3659);
var rounded = value.toFixed(1);
console.log(rounded);
Prints 118.3 to the console.
Note that using toFixed(2) will give the value as 118.29.
Hope this helps!

Haven't tested this extensively, but the function below should emulate the 'MidPointToEven' rounding:
function roundMidPointToEven(d, f){
f = Math.pow(10, f || 0); // f = decimals, use 0 as default
let val = d * f, r = Math.round(val);
if(r & 1 == 1 && Math.sign(r) * (Math.round(val * 10) % 10) === 5)
r += val > r ? 1 : -1; //only if the rounded value is odd and the next rounded decimal would be 5: alter the outcome to the nearest even number
return r / f;
}
for(let d of [50 * 2.3659, 2.155,2.145, -2.155, 2.144444, 2.1, 2.5])
console.log(d, ' -> ', roundMidPointToEven(d, 2)); //test values correspond with outcome of rounding decimals in C#

Related

round, decimal places, javascript [duplicate]

in JavaScript, the typical way to round a number to N decimal places is something like:
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
console.log(roundNumber(0.1 + 0.2, 2));
console.log(roundNumber(2.1234, 2));
However this approach will round to a maximum of N decimal places while I want to always round to N decimal places. For example "2.0" would be rounded to "2".
Any ideas?
I think that there is a more simple approach to all given here, and is the method Number.toFixed() already implemented in JavaScript.
simply write:
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
etc...
I found a way. This is Christoph's code with a fix:
function toFixed(value, precision) {
var precision = precision || 0,
power = Math.pow(10, precision),
absValue = Math.abs(Math.round(value * power)),
result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));
if (precision > 0) {
var fraction = String(absValue % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
result += '.' + padding + fraction;
}
return result;
}
Read the details of repeating a character using an array constructor here if you are curious as to why I added the "+ 1".
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.)
There's always a better way for doing things. Use toPrecision -
var number = 51.93999999999761;
I would like to get four digits precision: 51.94
just do:
number.toPrecision(4);
the result will be: 51.94
This works for rounding to N digits (if you just want to truncate to N digits remove the Math.round call and use the Math.trunc one):
function roundN(value, digits) {
var tenToN = 10 ** digits;
return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}
Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you'd end up with some unexpectedly long decimal part (this is due to floating point arithmetics).
A user comment at Format number to always show 2 decimal places calls this technique scaling.
Some mention there are cases that don't round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead:
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
PHP-Like rounding Method
The code below can be used to add your own version of Math.round to your own namespace which takes a precision parameter. Unlike Decimal rounding in the example above, this performs no conversion to and from strings, and the precision parameter works same way as PHP and Excel whereby a positive 1 would round to 1 decimal place and -1 would round to the tens.
var myNamespace = {};
myNamespace.round = function(number, precision) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};
myNamespace.round(1234.5678, 1); // 1234.6
myNamespace.round(1234.5678, -1); // 1230
from Mozilla Developer reference for Math.round()
Hopefully working code (didn't do much testing):
function toFixed(value, precision) {
var precision = precision || 0,
neg = value < 0,
power = Math.pow(10, precision),
value = Math.round(value * power),
integral = String((neg ? Math.ceil : Math.floor)(value / power)),
fraction = String((neg ? -value : value) % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
return precision ? integral + '.' + padding + fraction : integral;
}
I think below function can help
function roundOff(value,round) {
return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}
usage : roundOff(600.23458,2); will return 600.23
function roundton(num, n) {
return Number(num.toFixed(n));
}
This uses JS's built-in method Number.prototype.toFixed which is meant for formatting strings but allows us to round to a specific number of digits. the Number() call converts it back to a number object cleanly
Ideally, we wouldn't need to convert it to a string, but toFixed is written in native C++ doing basic cstring operations so it's likely still fast.
If you do not really care about rounding, just added a toFixed(x) and then removing trailing 0es and the dot if necessary. It is not a fast solution.
function format(value, decimals) {
if (value) {
value = value.toFixed(decimals);
} else {
value = "0";
}
if (value.indexOf(".") < 0) { value += "."; }
var dotIdx = value.indexOf(".");
while (value.length - dotIdx <= decimals) { value += "0"; } // add 0's
return value;
}

How to ceil decimal places in float? [duplicate]

Can you round a number in javascript to 1 character after the decimal point (properly rounded)?
I tried the *10, round, /10 but it leaves two decimals at the end of the int.
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"
var number = 123.456;
console.log(number.toFixed(1)); // should round to 123.5
If you use Math.round(5.01) you will get 5 instead of 5.0.
If you use toFixed you run into rounding issues.
If you want the best of both worlds, combine the two:
(Math.round(5.01 * 10) / 10).toFixed(1)
You might want to create a function for this:
function roundedToFixed(input, digits){
var rounder = Math.pow(10, digits);
return (Math.round(input * rounder) / rounder).toFixed(digits);
}
lodash has a round method:
_.round(4.006);
// => 4
_.round(4.006, 2);
// => 4.01
_.round(4060, -2);
// => 4100
Docs.
Source.
You can simply do the following:
let n = 1.25
let result = Number(n).toFixed(1)
// output string: 1.3
I vote for toFixed(), but, for the record, here's another way that uses bit shifting to cast the number to an int. So, it always rounds towards zero (down for positive numbers, up for negatives).
var rounded = ((num * 10) << 0) * 0.1;
But hey, since there are no function calls, it's wicked fast. :)
And here's one that uses string matching:
var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');
I don't recommend using the string variant, just sayin.
Try with this:
var original=28.453
// 1.- round "original" to two decimals
var result = Math.round (original * 100) / 100 //returns 28.45
// 2.- round "original" to 1 decimal
var result = Math.round (original * 10) / 10 //returns 28.5
// 3.- round 8.111111 to 3 decimals
var result = Math.round (8.111111 * 1000) / 1000 //returns 8.111
less complicated and easier to implement...
with this, you can create a function to do:
function RoundAndFix (n, d) {
var m = Math.pow (10, d);
return Math.round (n * m) / m;
}
function RoundAndFix (n, d) {
var m = Math.pow (10, d);
return Math.round (n * m) / m;
}
console.log (RoundAndFix(8.111111, 3));
EDIT: see this How to round using ROUND HALF UP. Rounding mode that most of us were taught in grade school
Why not just
let myNumber = 213.27321;
+myNumber.toFixed(1); // => 213.3
toFixed:
returns a string representing the given number using fixed-point notation.
Unary plus (+): The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.
In general, decimal rounding is done by scaling: round(num * p) / p
Naive implementation
Using the following function with halfway numbers, you will get either the upper rounded value as expected, or the lower rounded value sometimes depending on the input.
This inconsistency in rounding may introduce hard to detect bugs in the client code.
function naiveRound(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
return Math.round(num * p) / p;
}
console.log( naiveRound(1.245, 2) ); // 1.25 correct (rounded as expected)
console.log( naiveRound(1.255, 2) ); // 1.25 incorrect (should be 1.26)
Better implementations
By converting the number to a string in the exponential notation, positive numbers are rounded as expected.
But, be aware that negative numbers round differently than positive numbers.
In fact, it performs what is basically equivalent to "round half up" as the rule, you will see that round(-1.005, 2) evaluates to -1 even though round(1.005, 2) evaluates to 1.01. The lodash _.round method uses this technique.
/**
* Round half up ('round half towards positive infinity')
* Uses exponential notation to avoid floating-point issues.
* Negative numbers round differently than positive numbers.
*/
function round(num, decimalPlaces) {
num = Math.round(num + "e" + decimalPlaces);
return Number(num + "e" + -decimalPlaces);
}
// test rounding of half
console.log( round(0.5, 0) ); // 1
console.log( round(-0.5, 0) ); // 0
// testing edge cases
console.log( round(1.005, 2) ); // 1.01
console.log( round(2.175, 2) ); // 2.18
console.log( round(5.015, 2) ); // 5.02
console.log( round(-1.005, 2) ); // -1
console.log( round(-2.175, 2) ); // -2.17
console.log( round(-5.015, 2) ); // -5.01
If you want the usual behavior when rounding negative numbers, you would need to convert negative numbers to positive before calling Math.round(), and then convert them back to negative numbers before returning.
// Round half away from zero
function round(num, decimalPlaces) {
num = Math.round(Math.abs(num) + "e" + decimalPlaces) * Math.sign(num);
return Number(num + "e" + -decimalPlaces);
}
There is a different purely mathematical technique to perform round-to-nearest (using "round half away from zero"), in which epsilon correction is applied before calling the rounding function.
Simply, we add the smallest possible float value (= 1.0 ulp; unit in the last place) to the number before rounding. This moves to the next representable value after the number, away from zero.
/**
* Round half away from zero ('commercial' rounding)
* Uses correction to offset floating-point inaccuracies.
* Works symmetrically for positive and negative numbers.
*/
function round(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
var e = Number.EPSILON * num * p;
return Math.round((num * p) + e) / p;
}
// test rounding of half
console.log( round(0.5, 0) ); // 1
console.log( round(-0.5, 0) ); // -1
// testing edge cases
console.log( round(1.005, 2) ); // 1.01
console.log( round(2.175, 2) ); // 2.18
console.log( round(5.015, 2) ); // 5.02
console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02
This is needed to offset the implicit round-off error that may occur during encoding of decimal numbers, particularly those having "5" in the last decimal position, like 1.005, 2.675 and 16.235. Actually, 1.005 in decimal system is encoded to 1.0049999999999999 in 64-bit binary float; while, 1234567.005 in decimal system is encoded to 1234567.0049999998882413 in 64-bit binary float.
It is worth noting that the maximum binary round-off error is dependent upon (1) the magnitude of the number and (2) the relative machine epsilon (2^-52).
Using toPrecision method:
var a = 1.2345
a.toPrecision(2)
// result "1.2"
var num = 34.7654;
num = Math.round(num * 10) / 10;
console.log(num); // Logs: 34.8
To complete the Best Answer:
var round = function ( number, precision )
{
precision = precision || 0;
return parseFloat( parseFloat( number ).toFixed( precision ) );
}
The input parameter number may "not" always be a number, in this case .toFixed does not exist.
ES 6 Version of Accepted Answer:
function round(value, precision) {
const multiplier = 10 ** (precision || 0);
return Math.round(value * multiplier) / multiplier;
}
If your method does not work, plz post your code.
However,you could accomplish the rounding off task as:
var value = Math.round(234.567*100)/100
Will give you 234.56
Similarly
var value = Math.round(234.567*10)/10
Will give 234.5
In this way you can use a variable in the place of the constant as used above.
I made one that returns number type and also places decimals only if are needed (no 0 padding).
Examples:
roundWithMaxPrecision(11.234, 2); //11.23
roundWithMaxPrecision(11.234, 1); //11.2
roundWithMaxPrecision(11.234, 4); //11.23
roundWithMaxPrecision(11.234, -1); //10
roundWithMaxPrecision(4.2, 2); //4.2
roundWithMaxPrecision(4.88, 1); //4.9
The code:
function roundWithMaxPrecision (n, precision) {
const precisionWithPow10 = Math.pow(10, precision);
return Math.round(n * precisionWithPow10) / precisionWithPow10;
}
Little Angular filter if anyone wants it:
angular.module('filters').filter('decimalPlace', function() {
return function(num, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(num * multiplier) / multiplier;
};
});
use if via:
{{model.value| decimalPlace}}
{{model.value| decimalPlace:1}}
{{model.value| decimalPlace:2}}
:)
This seems to work reliably across anything I throw at it:
function round(val, multiplesOf) {
var s = 1 / multiplesOf;
var res = Math.ceil(val*s)/s;
res = res < val ? res + multiplesOf: res;
var afterZero = multiplesOf.toString().split(".")[1];
return parseFloat(res.toFixed(afterZero ? afterZero.length : 0));
}
It rounds up, so you may need to modify it according to use case. This should work:
console.log(round(10.01, 1)); //outputs 11
console.log(round(10.01, 0.1)); //outputs 10.1
If you care about proper rounding up then:
function roundNumericStrings(str , numOfDecPlacesRequired){
var roundFactor = Math.pow(10, numOfDecPlacesRequired);
return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString(); }
Else if you don't then you already have a reply from previous posts
str.slice(0, -1)
Math.round( num * 10) / 10 doesn't work.
For example, 1455581777.8-145558160.4 gives you 1310023617.3999999.
So only use num.toFixed(1)
I found a way to avoid the precision problems:
function badRound (num, precision) {
const x = 10 ** precision;
return Math.round(num * x) / x
}
// badRound(1.005, 2) --> 1
function round (num, precision) {
const x = 10 ** (precision + 1);
const y = 10 ** precision;
return Math.round(Math.round(num * x) / 10) / y
}
// round(1.005, 2) --> 1.01
Math.round( mul/count * 10 ) / 10
Math.round(Math.sqrt(sqD/y) * 10 ) / 10
Thanks
function rnd(v,n=2) {
return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(10,n)
}
this one catch the corner cases well
If your source code is typescript you could use a function like this:
public static ToFixedRounded(decimalNumber: number, fractionDigits: number): number {
var rounded = Math.pow(10, fractionDigits);
return (Math.round(decimalNumber * rounded) / rounded).toFixed(fractionDigits) as unknown as number;
}
const solds = 136780000000;
const number = (solds >= 1000000000 && solds < 1000000000000) ? { divisor: 1000000000, postfix: "B" }: (solds >= 1000000 && solds < 1000000000) ? { divisor: 1000000, postfix: "M" }: (solds >= 1000 && solds < 1000000) ? { divisor: 1000, postfix: "K" }: { divisor: 1, postfix: null };
const floor = Math.floor(solds / number.divisor).toLocaleString();
const firstDecimalIndex = solds.toLocaleString().charAt(floor.length+1);
const final =firstDecimalIndex.match("0")? floor + number.postfix: floor + "." + firstDecimalIndex + number.postfix;
console.log(final);
136780000000 --> 136.7B
1367800 --> 1.3M
1342 --> 1.3K

How to round Decimal result in javascript [duplicate]

Can you round a number in javascript to 1 character after the decimal point (properly rounded)?
I tried the *10, round, /10 but it leaves two decimals at the end of the int.
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"
var number = 123.456;
console.log(number.toFixed(1)); // should round to 123.5
If you use Math.round(5.01) you will get 5 instead of 5.0.
If you use toFixed you run into rounding issues.
If you want the best of both worlds, combine the two:
(Math.round(5.01 * 10) / 10).toFixed(1)
You might want to create a function for this:
function roundedToFixed(input, digits){
var rounder = Math.pow(10, digits);
return (Math.round(input * rounder) / rounder).toFixed(digits);
}
lodash has a round method:
_.round(4.006);
// => 4
_.round(4.006, 2);
// => 4.01
_.round(4060, -2);
// => 4100
Docs.
Source.
You can simply do the following:
let n = 1.25
let result = Number(n).toFixed(1)
// output string: 1.3
I vote for toFixed(), but, for the record, here's another way that uses bit shifting to cast the number to an int. So, it always rounds towards zero (down for positive numbers, up for negatives).
var rounded = ((num * 10) << 0) * 0.1;
But hey, since there are no function calls, it's wicked fast. :)
And here's one that uses string matching:
var rounded = (num + '').replace(/(^.*?\d+)(\.\d)?.*/, '$1$2');
I don't recommend using the string variant, just sayin.
Try with this:
var original=28.453
// 1.- round "original" to two decimals
var result = Math.round (original * 100) / 100 //returns 28.45
// 2.- round "original" to 1 decimal
var result = Math.round (original * 10) / 10 //returns 28.5
// 3.- round 8.111111 to 3 decimals
var result = Math.round (8.111111 * 1000) / 1000 //returns 8.111
less complicated and easier to implement...
with this, you can create a function to do:
function RoundAndFix (n, d) {
var m = Math.pow (10, d);
return Math.round (n * m) / m;
}
function RoundAndFix (n, d) {
var m = Math.pow (10, d);
return Math.round (n * m) / m;
}
console.log (RoundAndFix(8.111111, 3));
EDIT: see this How to round using ROUND HALF UP. Rounding mode that most of us were taught in grade school
Why not just
let myNumber = 213.27321;
+myNumber.toFixed(1); // => 213.3
toFixed:
returns a string representing the given number using fixed-point notation.
Unary plus (+): The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.
In general, decimal rounding is done by scaling: round(num * p) / p
Naive implementation
Using the following function with halfway numbers, you will get either the upper rounded value as expected, or the lower rounded value sometimes depending on the input.
This inconsistency in rounding may introduce hard to detect bugs in the client code.
function naiveRound(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
return Math.round(num * p) / p;
}
console.log( naiveRound(1.245, 2) ); // 1.25 correct (rounded as expected)
console.log( naiveRound(1.255, 2) ); // 1.25 incorrect (should be 1.26)
Better implementations
By converting the number to a string in the exponential notation, positive numbers are rounded as expected.
But, be aware that negative numbers round differently than positive numbers.
In fact, it performs what is basically equivalent to "round half up" as the rule, you will see that round(-1.005, 2) evaluates to -1 even though round(1.005, 2) evaluates to 1.01. The lodash _.round method uses this technique.
/**
* Round half up ('round half towards positive infinity')
* Uses exponential notation to avoid floating-point issues.
* Negative numbers round differently than positive numbers.
*/
function round(num, decimalPlaces) {
num = Math.round(num + "e" + decimalPlaces);
return Number(num + "e" + -decimalPlaces);
}
// test rounding of half
console.log( round(0.5, 0) ); // 1
console.log( round(-0.5, 0) ); // 0
// testing edge cases
console.log( round(1.005, 2) ); // 1.01
console.log( round(2.175, 2) ); // 2.18
console.log( round(5.015, 2) ); // 5.02
console.log( round(-1.005, 2) ); // -1
console.log( round(-2.175, 2) ); // -2.17
console.log( round(-5.015, 2) ); // -5.01
If you want the usual behavior when rounding negative numbers, you would need to convert negative numbers to positive before calling Math.round(), and then convert them back to negative numbers before returning.
// Round half away from zero
function round(num, decimalPlaces) {
num = Math.round(Math.abs(num) + "e" + decimalPlaces) * Math.sign(num);
return Number(num + "e" + -decimalPlaces);
}
There is a different purely mathematical technique to perform round-to-nearest (using "round half away from zero"), in which epsilon correction is applied before calling the rounding function.
Simply, we add the smallest possible float value (= 1.0 ulp; unit in the last place) to the number before rounding. This moves to the next representable value after the number, away from zero.
/**
* Round half away from zero ('commercial' rounding)
* Uses correction to offset floating-point inaccuracies.
* Works symmetrically for positive and negative numbers.
*/
function round(num, decimalPlaces) {
var p = Math.pow(10, decimalPlaces);
var e = Number.EPSILON * num * p;
return Math.round((num * p) + e) / p;
}
// test rounding of half
console.log( round(0.5, 0) ); // 1
console.log( round(-0.5, 0) ); // -1
// testing edge cases
console.log( round(1.005, 2) ); // 1.01
console.log( round(2.175, 2) ); // 2.18
console.log( round(5.015, 2) ); // 5.02
console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02
This is needed to offset the implicit round-off error that may occur during encoding of decimal numbers, particularly those having "5" in the last decimal position, like 1.005, 2.675 and 16.235. Actually, 1.005 in decimal system is encoded to 1.0049999999999999 in 64-bit binary float; while, 1234567.005 in decimal system is encoded to 1234567.0049999998882413 in 64-bit binary float.
It is worth noting that the maximum binary round-off error is dependent upon (1) the magnitude of the number and (2) the relative machine epsilon (2^-52).
Using toPrecision method:
var a = 1.2345
a.toPrecision(2)
// result "1.2"
var num = 34.7654;
num = Math.round(num * 10) / 10;
console.log(num); // Logs: 34.8
To complete the Best Answer:
var round = function ( number, precision )
{
precision = precision || 0;
return parseFloat( parseFloat( number ).toFixed( precision ) );
}
The input parameter number may "not" always be a number, in this case .toFixed does not exist.
ES 6 Version of Accepted Answer:
function round(value, precision) {
const multiplier = 10 ** (precision || 0);
return Math.round(value * multiplier) / multiplier;
}
If your method does not work, plz post your code.
However,you could accomplish the rounding off task as:
var value = Math.round(234.567*100)/100
Will give you 234.56
Similarly
var value = Math.round(234.567*10)/10
Will give 234.5
In this way you can use a variable in the place of the constant as used above.
I made one that returns number type and also places decimals only if are needed (no 0 padding).
Examples:
roundWithMaxPrecision(11.234, 2); //11.23
roundWithMaxPrecision(11.234, 1); //11.2
roundWithMaxPrecision(11.234, 4); //11.23
roundWithMaxPrecision(11.234, -1); //10
roundWithMaxPrecision(4.2, 2); //4.2
roundWithMaxPrecision(4.88, 1); //4.9
The code:
function roundWithMaxPrecision (n, precision) {
const precisionWithPow10 = Math.pow(10, precision);
return Math.round(n * precisionWithPow10) / precisionWithPow10;
}
Little Angular filter if anyone wants it:
angular.module('filters').filter('decimalPlace', function() {
return function(num, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(num * multiplier) / multiplier;
};
});
use if via:
{{model.value| decimalPlace}}
{{model.value| decimalPlace:1}}
{{model.value| decimalPlace:2}}
:)
This seems to work reliably across anything I throw at it:
function round(val, multiplesOf) {
var s = 1 / multiplesOf;
var res = Math.ceil(val*s)/s;
res = res < val ? res + multiplesOf: res;
var afterZero = multiplesOf.toString().split(".")[1];
return parseFloat(res.toFixed(afterZero ? afterZero.length : 0));
}
It rounds up, so you may need to modify it according to use case. This should work:
console.log(round(10.01, 1)); //outputs 11
console.log(round(10.01, 0.1)); //outputs 10.1
If you care about proper rounding up then:
function roundNumericStrings(str , numOfDecPlacesRequired){
var roundFactor = Math.pow(10, numOfDecPlacesRequired);
return (Math.round(parseFloat(str)*roundFactor)/roundFactor).toString(); }
Else if you don't then you already have a reply from previous posts
str.slice(0, -1)
Math.round( num * 10) / 10 doesn't work.
For example, 1455581777.8-145558160.4 gives you 1310023617.3999999.
So only use num.toFixed(1)
I found a way to avoid the precision problems:
function badRound (num, precision) {
const x = 10 ** precision;
return Math.round(num * x) / x
}
// badRound(1.005, 2) --> 1
function round (num, precision) {
const x = 10 ** (precision + 1);
const y = 10 ** precision;
return Math.round(Math.round(num * x) / 10) / y
}
// round(1.005, 2) --> 1.01
Math.round( mul/count * 10 ) / 10
Math.round(Math.sqrt(sqD/y) * 10 ) / 10
Thanks
function rnd(v,n=2) {
return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(10,n)
}
this one catch the corner cases well
If your source code is typescript you could use a function like this:
public static ToFixedRounded(decimalNumber: number, fractionDigits: number): number {
var rounded = Math.pow(10, fractionDigits);
return (Math.round(decimalNumber * rounded) / rounded).toFixed(fractionDigits) as unknown as number;
}
const solds = 136780000000;
const number = (solds >= 1000000000 && solds < 1000000000000) ? { divisor: 1000000000, postfix: "B" }: (solds >= 1000000 && solds < 1000000000) ? { divisor: 1000000, postfix: "M" }: (solds >= 1000 && solds < 1000000) ? { divisor: 1000, postfix: "K" }: { divisor: 1, postfix: null };
const floor = Math.floor(solds / number.divisor).toLocaleString();
const firstDecimalIndex = solds.toLocaleString().charAt(floor.length+1);
const final =firstDecimalIndex.match("0")? floor + number.postfix: floor + "." + firstDecimalIndex + number.postfix;
console.log(final);
136780000000 --> 136.7B
1367800 --> 1.3M
1342 --> 1.3K

JavaScript math, round to two decimal places [duplicate]

This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
Closed 5 years ago.
I have the following JavaScript syntax:
var discount = Math.round(100 - (price / listprice) * 100);
This rounds up to the whole number. How can I return the result with 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/
If you use a unary plus to convert a string to a number as documented on MDN.
For example:+discount.toFixed(2)
The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.
You can use following to solve this issue:
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
Add .toFixed(2) to get the two decimal places you wanted.
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
You could make a function that will handle the rounding for you:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
Example:
https://jsfiddle.net/k5tpq3pd/36/
Alternative
You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.
Number.prototype.round = function(decimals) {
return Number((Math.round(this + "e" + decimals) + "e-" + decimals));
}
and use it like this:
var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
Example
https://jsfiddle.net/k5tpq3pd/35/
Source: http://www.jacklmoore.com/notes/rounding-in-javascript/
To get the result with two decimals, you can do like this :
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.
The best and simple solution I found is
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01
try using discount.toFixed(2);
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
A small variation on the accepted answer.
toFixed(2) returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:
var discount = + ((price / listprice).toFixed(2));
Edited:
I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to
var discount = Math.round(price / listprice * 100) / 100;
This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
Fastest Way - faster than toFixed():
TWO DECIMALS
x = .123456
result = Math.round(x * 100) / 100 // result .12
THREE DECIMALS
x = .123456
result = Math.round(x * 1000) / 1000 // result .123
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)
Here is a working example
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24
To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.
var testNum = 134.9567654;
var decPl = 2;
var testRes = roundDec(testNum,decPl);
alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
function roundDec(nbr,dec_places){
var mult = Math.pow(10,dec_places);
return Math.round(nbr * mult) / mult;
}

Javascript: formatting a rounded number to N decimals

in JavaScript, the typical way to round a number to N decimal places is something like:
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
function roundNumber(num, dec) {
return Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
}
console.log(roundNumber(0.1 + 0.2, 2));
console.log(roundNumber(2.1234, 2));
However this approach will round to a maximum of N decimal places while I want to always round to N decimal places. For example "2.0" would be rounded to "2".
Any ideas?
I think that there is a more simple approach to all given here, and is the method Number.toFixed() already implemented in JavaScript.
simply write:
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
etc...
I found a way. This is Christoph's code with a fix:
function toFixed(value, precision) {
var precision = precision || 0,
power = Math.pow(10, precision),
absValue = Math.abs(Math.round(value * power)),
result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));
if (precision > 0) {
var fraction = String(absValue % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
result += '.' + padding + fraction;
}
return result;
}
Read the details of repeating a character using an array constructor here if you are curious as to why I added the "+ 1".
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.)
There's always a better way for doing things. Use toPrecision -
var number = 51.93999999999761;
I would like to get four digits precision: 51.94
just do:
number.toPrecision(4);
the result will be: 51.94
This works for rounding to N digits (if you just want to truncate to N digits remove the Math.round call and use the Math.trunc one):
function roundN(value, digits) {
var tenToN = 10 ** digits;
return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}
Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you'd end up with some unexpectedly long decimal part (this is due to floating point arithmetics).
A user comment at Format number to always show 2 decimal places calls this technique scaling.
Some mention there are cases that don't round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead:
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
PHP-Like rounding Method
The code below can be used to add your own version of Math.round to your own namespace which takes a precision parameter. Unlike Decimal rounding in the example above, this performs no conversion to and from strings, and the precision parameter works same way as PHP and Excel whereby a positive 1 would round to 1 decimal place and -1 would round to the tens.
var myNamespace = {};
myNamespace.round = function(number, precision) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = Math.round(tempNumber);
return roundedTempNumber / factor;
};
myNamespace.round(1234.5678, 1); // 1234.6
myNamespace.round(1234.5678, -1); // 1230
from Mozilla Developer reference for Math.round()
Hopefully working code (didn't do much testing):
function toFixed(value, precision) {
var precision = precision || 0,
neg = value < 0,
power = Math.pow(10, precision),
value = Math.round(value * power),
integral = String((neg ? Math.ceil : Math.floor)(value / power)),
fraction = String((neg ? -value : value) % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
return precision ? integral + '.' + padding + fraction : integral;
}
I think below function can help
function roundOff(value,round) {
return (parseInt(value * (10 ** (round + 1))) - parseInt(value * (10 ** round)) * 10) > 4 ? (((parseFloat(parseInt((value + parseFloat(1 / (10 ** round))) * (10 ** round))))) / (10 ** round)) : (parseFloat(parseInt(value * (10 ** round))) / ( 10 ** round));
}
usage : roundOff(600.23458,2); will return 600.23
function roundton(num, n) {
return Number(num.toFixed(n));
}
This uses JS's built-in method Number.prototype.toFixed which is meant for formatting strings but allows us to round to a specific number of digits. the Number() call converts it back to a number object cleanly
Ideally, we wouldn't need to convert it to a string, but toFixed is written in native C++ doing basic cstring operations so it's likely still fast.
If you do not really care about rounding, just added a toFixed(x) and then removing trailing 0es and the dot if necessary. It is not a fast solution.
function format(value, decimals) {
if (value) {
value = value.toFixed(decimals);
} else {
value = "0";
}
if (value.indexOf(".") < 0) { value += "."; }
var dotIdx = value.indexOf(".");
while (value.length - dotIdx <= decimals) { value += "0"; } // add 0's
return value;
}

Categories