Take the 2-minute tour ×

I want to do some math like plus, minus etc. with decimal values.

So i wrote two functions;

function to_decimal(i){
    var $dec = parseFloat(i);
    return $dec.toFixed(2);

function calc_price(){
    var $t = $('#sub_total .total').text();
    var $total = to_decimal($t);

    $('#price_list ul li').each(function(){
        var $p = to_decimal($(this).find('.item_price').text());
        $total = $total + $p;

    $t = $('#sub_total .total').text($total);

But these functions not working correctly i think because the result is returning string like 0.0010.30

Where is the problem?

share|improve this question
toFixed returns a string. –  Felix Kling Jul 27 '11 at 13:43

3 Answers 3

up vote 5 down vote accepted

You need to add a + infront of that statement and you're fine:

return +$dec.toFixed(2);

That will convert the string into a number. If the string cannot get converted, it'll return the NaN value.

share|improve this answer
As an equivalent alternative, I often use $dec.toFixed(2) * 1 instead (multiplication by one). I feel like I'm more likely to notice my intent later; the + can be hard to miss. –  lwburk Jul 27 '11 at 13:50

Instead of:

return $dec.toFixed(2);


return Math.round($dec*100)/100;
share|improve this answer

The toFixed method returns a string. Any mathematical operation that doesn't affect the output can be used to convert the string to a number (except addition, whose operator unfortunately doubles as the string concatenation operator):

$dec.toFixed(2) - 0 
$dec.toFixed(2) / 1 
$dec.toFixed(2) * 1

These are the fastest methods. However, if speed is not a concern (and it probably isn't when performing a small number of operations) then the clearest, most-readable method to convert a string to a number is the Number constructor:


Edit: The performance information above may no longer be universally true. The Number constructor is indeed considerably slower than each of the alternatives in IE 7.0 and Firefox 5, but actually performs the best in Chrome 12.0.742.


share|improve this answer
Thank you. I learned something from your post. But jAndy's response is worked fine. –  R. Canser Yanbakan Jul 27 '11 at 14:11

Your Answer


