开发者

Not able to format resulting number into decimal form

Why would this not show #total as a decimal? The value of the inputs in class="total" are a function result that stores the value in 2 decimal format. The function to display the row totals works fine but when I use the below code to total the rows when the qty field changes, the mat is correct and the change takes place correctly, but it in an int style not a currency format (2 decimal places). I have tried toPrecision as well with no change.

$('[name^=qty]').change(function(){
    var sum = 0;
 开发者_高级运维   $('input.total').each(function() {
        sum += $(this).val();
    });

    $('#total').val(sum).toFixed(2);
    });

Here is the code that totals each row

function Tot(x,price,y) {
var total = CurrencyFormatted(x*price);
var v = document.getElementById(y);
v.setAttribute('value',total);}

All of these functions run just fine, totaling correctly and updating as expected, with exception to the decimal places in the grand total field.

Below is the html that I am using for each row and then the total

<td>$<input id="t1" disabled="disabled" size="8" value="0.00" class="total" />
...
<input disabled="disabled" id="total" name="total" size="8" value="0.00" />

There is nothing in the css that would change the format of the number either in the class or the table structure. I am at a complete loss, but hopefully someone will see something I don't. Thank you in advance.


$('input.total').each(function() {
    sum += parseFloat( $(this).val() );
});

$('#total').val( sum.toFixed(2) );

EDIT, since i was busy i didn't explain my answer, Greg Pettit did, so here's the explanation

You were trying to chain toFixed() to something that's not a number. Also, you weren't converting your retrieved values to floats. JS may have handled the latter, but better to run it through parseFloat as per sample


You can use the parseFloat function to do it:

parseFloat(value).toFixed(2);

for more examples:

JQuery Type examples


val returns a String object, not a number. you'll need to call parseFloat or cast to Number before calling toFixed(2)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜