Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding to the nearest hundredth of a decimal in JavaScript

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.

like image 580
Spencer Carpenter Avatar asked Feb 19 '13 22:02

Spencer Carpenter


1 Answers

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.


ORIGINAL (SOMEWHAT INCORRECT) ANSWER

//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;
}
like image 139
Rodaine Avatar answered Oct 11 '22 04:10

Rodaine