I have the following math operation, and the worst thing is, this operation handles monetary values.
3898.95 / 3.0
If you do this operation on the calculator the result will be equal to: 1299,65
exact.
But with JavaScript the result will be equal to: 1299,649999999999
, just put this operation on an alert you will see the result.
And in my application it accepts only 2 decimals after the comma and truncates the rest with the use of a filter in the AngularJS, that is, in an installment it will always be missing a few cents since the result will be 1299,64
.
Filter on AngularJS:
app.filter("currencyRounded",function(){
return function(val){
return truncateDecimals(val, 2);
}
});
Functions that the filter execution calls:
function truncateDecimals (num, digits) {
if (num == undefined) num = 0.0;
var numS = num.toString(),
decPos = numS.indexOf('.'),
substrLength = decPos == -1 ? numS.length : 1 + decPos + digits,
trimmedResult = numS.substr(0, substrLength),
finalResult = isNaN(trimmedResult) ? 0 : trimmedResult;
return formatOnlyNumber(parseFloat(finalResult)).replace(/\./g,',');
}
function formatOnlyNumber(valor){
return parseFloat(Math.round(valor * 100) / 100).toFixed(2);
}
But the main question is, how do you have 1299,65
as a result? If it is just using JavaScript without any other better function yet.