0

I am using the following code snippet to calculate a total price. This works great except #totalPrice on some occasions expands out to for example $267.9999999999. How do I reformat #totalPrice within this function to just round to two decimals as is standard in dealing with price.

function getTotalCost(inventory) {
    if(inventory) {
        getTotalParts(inventory);
        getTotalMarkup(inventory);
    }

    var labor = $('#labor').val() * 1;
    var totals = 0;
    for(i in totalMarkup) {
        totals += totalMarkup[i];
    }
    totalCost = totals+labor;
    /*if(totals == 0) {
        totalCost = 0;
    }*/
    $('#totalPrice').html(totalCost);
}
nickb
  • 56,839
  • 11
  • 91
  • 130
Rocco The Taco
  • 3,463
  • 9
  • 40
  • 76

3 Answers3

1

When working with javascript the floating points are always a bad. Best you can do is, round it up.

But in this case you can do

(totalCost).toFixed(2);
Raab
  • 31,764
  • 4
  • 47
  • 63
fmsf
  • 33,514
  • 48
  • 140
  • 190
1

You can have:

$('#totalPrice').html(totalCost.toFixed(2));

See:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed

Notice that toFixed method returns a formatted number, therefore converts the number to a string. It's not a problem here because html wants a string, but it's keep it in mind that in order to avoid concatenation of string when you expects sum of numbers. I believe you use $('#labor').val() * 1; for this very reason. However it's not necessary, it's better use method like parseFloat or the unary plus operator:

var labor = +$('#labor').val();
ZER0
  • 22,173
  • 4
  • 45
  • 51
  • excellent, thanks for the help. Just so I know why is it better to use parseFloat or unary? – Rocco The Taco Jul 03 '12 at 19:33
  • It depends from what is the input you have. I usually prefer the unary plus because it's an operator therefore is not a function call. But sometimes `parseFloat` does a better job if I want actually "parse" (as the method said) the input string and not just convert. Ti give some concrete example, if you have `+"31.40 USD"` you will get `NaN`. Instead, with `parseFloat("31.40 USD")` you will have `31.4` as number. See the link I gave in my answer for further details – ZER0 Jul 03 '12 at 19:53
0

You can use Math.round function in JavaScript like this.

totalCost = Math.round(totalCost*100)/100;
$('#totalPrice').html(totalCost);
Sylvain B
  • 522
  • 3
  • 9