I'm trying to round a float number in Javascript in the same way that I do it in PHP; but I can not make both languages round in the same way the following number:6.404999999999999
When I use PHP round I get: 6.41
, but when I trying to round with Javascript I always get 6.40
INFO: The correct answer is https://stackoverflow.com/a/54721202/4359029
My Javascript attempts:
Attempt #1:
module.exports = function round (value, precision, mode) {
var m, f, isHalf, sgn // helper variables
// making sure precision is integer
precision |= 0
m = Math.pow(10, precision)
value *= m
// sign of the number
sgn = (value > 0) | -(value < 0)
isHalf = value % 1 === 0.5 * sgn
f = Math.floor(value)
if (isHalf) {
switch (mode) {
case 'PHP_ROUND_HALF_DOWN':
// rounds .5 toward zero
value = f + (sgn < 0)
break
case 'PHP_ROUND_HALF_EVEN':
// rouds .5 towards the next even integer
value = f + (f % 2 * sgn)
break
case 'PHP_ROUND_HALF_ODD':
// rounds .5 towards the next odd integer
value = f + !(f % 2)
break
default:
// rounds .5 away from zero
value = f + (sgn > 0)
}
}
return (isHalf ? value : Math.round(value)) / m
}
Extracted from: http://locutus.io/php/math/round/
Attempt #2:
round(decimal: number, decimalPoints: number): number{
let roundedValue = Math.round(decimal * Math.pow(10, decimalPoints)) / Math.pow(10, decimalPoints);
console.log(`Rounded ${decimal} to ${roundedValue}`);
return roundedValue;
}
Extracted from: https://stackoverflow.com/a/50918962/4359029
I tried with other solutions... but without success.
Could someone tell me how to get the rounding of Javascript to act like PHP's?
Could you tell me why they work in different ways in the case I explain?