Javascript:为什么这会产生难看的字符串???我想要货币 [英] Javascript: why does this produce and ugly string??? I would like currency

查看:36
本文介绍了Javascript:为什么这会产生难看的字符串???我想要货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var total = 0;
$(".amount").each(function () {
    var value = $(this).val();
    value = (value.length < 1) ? 0 : value;
    var tmp = parseFloat(value).toFixed(2);
    total += tmp;
});
$(".total").text(total);

我试图遍历一些文本框并总结其值.这会产生讨厌的字符串.我想念什么?如果我在第一个文本框中输入8,则总文本最终为"08.000.000.000.00".我究竟做错了什么?我想将其格式化为货币,但如果不是,则至少应为两个十进制数字.有指针吗?

I am trying to loop through some text boxes and sum up their values. This produces a nasty string. What am I missing?? if I put 8 in the first textbox total text ends up as " 08.000.000.000.00". What am I doing wrong? I would like to format as currency but if not, at least just a two decimal number. Any pointers?

推荐答案

.toFixed将对象从数字转换为字符串.

.toFixed converts the object from a Number to a String.

保留所有值,仅在最后使用.toFixed进行转换

Leave the full values in place and only convert using .toFixed at the very end

$(".total").text(total.toFixed(2));

或者,将字符串转换回数字.

Alternatively, convert the string back to a number.

total = total + + tmp;

这篇关于Javascript:为什么这会产生难看的字符串???我想要货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆