Whatever language you choose, you may encounter a rounding problem. In fact, this is due to the limit of the required number of bits needed to get the right number after a calculation.
Simple example:
In javascript (like any other language), you may want to use a function to round the result after even a simple sum (with decimals) :
Unfortunately it's not always working as we expect.
That's why I created my own function which is based on a string version. I read every char and make the round by myself so I'm not limited by the number of bits.
round(number, decimalsLength) {
// If the number does contains a scientific notation, we use a more traditionnal calculation method
if(number.toString().includes("e"))
number = parseFloat(number.toFixed(4));
// Split the integer part and the decimal part
var number = (typeof number === "number") ? number : (number != null) ? parseFloat(number) : 0; // Return NaN for [null; {}]
var decimalsLength = decimalsLength || 0;
var array = (number+"").split(".");
var left = array[0];
var right = "1"+(array[1] || 0); // We add 1 to keep the left 0
// Round only if we have more decimal than needed
if(right.length-1 >= decimalsLength) {
// Round up
if(parseInt(right.substr(decimalsLength+1, 1)) >= 5)
right = parseInt(right.substr(0, decimalsLength+1))+1;
// If we moved to the upper integer
if(right.toString().substr(0, 1) == 2) { // If the added 1 has became a 2
var noDecimal = parseInt(right.toString().substr(1, decimalsLength)) == 0; // Return an integer if we no longer have any decimal
left = (parseInt(left) + (number > 0 ? 1 : -1)).toString();
return parseFloat(left + (noDecimal ?"":".") + (noDecimal?"":right.toString().substr(1, decimalsLength)));
}
}
// Else, we don't need to round
var noDecimal = parseInt(right.toString().substr(1, decimalsLength)) == 0;
return parseFloat(left + (noDecimal?"":".") + (noDecimal?"":right.toString().substr(1, decimalsLength)));
}
I wanted to share this with you in case it can help, but also to have a feedback and improve the function if you find it useful.