I'm doing simple math in JavaScript using variables to represent the numbers. Here is an example of my code:
var ones = 0;
var fives = 0;
function results (){
_fives = (fives * 5);
var res = (_fives + ones);
document.innerHTML = res;
}
This isn't the full code but basically I'm having the user enter the amount of bills and coins from 1 cent coins up to $100 bills. The code multiplies the amount of bills to the amount the bill is worth. This is no problem works just fine... For some reason on some of my results it shows a decimal like 1.899999999997 not sure how this is happening.
Is there a way to change this so it round to the nearest hundredth of a decimal?
For example instead of it showing 1.89999999997 it would just show 1.90 in reality this isn't a big issue. This is a personal thing that I can just round it myself however it would be nice to learn how to do this for future reference.
UPDATE: MDN actually has a great example of decimal rounding that avoids floating point inaccuracies. Their method can be modified to always round up, based on the OP.
//to round to n decimal places
function round(num, places) {
var multiplier = Math.pow(10, places);
return Math.round(num * multiplier) / multiplier;
}
EDIT: I didn't read the question completely. Since we're talking currency, we probably want to round it up:
//to round up to two decimal places
function money_round(num) {
return Math.ceil(num * 100) / 100;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With