想知道是否有人可以阐明为什么我的小计是1,并且.00被从小计中剥离。JavaScript从我的小数中剥离.00?
价为1.00,而itemQty为1
var price = parseFloat(res.productPrice).toFixed(2);
var subTotal = price * parseInt(res.itemQty);
想知道是否有人可以阐明为什么我的小计是1,并且.00被从小计中剥离。JavaScript从我的小数中剥离.00?
价为1.00,而itemQty为1
var price = parseFloat(res.productPrice).toFixed(2);
var subTotal = price * parseInt(res.itemQty);
var price = parseFloat(res.productPrice).toFixed(2);
var subTotal = (price * parseInt(res.itemQty)).toFixed(2);
您必须在subTotal上调用toFixed()
才能返回字符串而不是数字。
你必须再次转换小计toFixed()
,因为它是一个数字。
1
和1.00
在数字上是相同的东西。
toFixed()
产生一个字符串。字符串几乎是唯一的意义,其中1.00
和1
是两个不同的值。
在price * parseInt(res.itemQty)
您正在使用数字操作中的"1.00"
字符串,因此该值将被解释为数字。 subTotal
将是一个数字,因为它是数字运算的结果,因此它同时是1
和1.00
。
如果想要用小数表示它,则需要再次使用toFixed
将其转换为字符串。
钉在头上。 – Sphvn 2012-07-25 09:25:04
因为你还没有使用toFixed做的小计字符串(2)
var res = {productPrice:3.00, itemQty:2}
var price = parseFloat(res.productPrice).toFixed(2);
var subTotal = price * parseInt(res.itemQty);
console.log(subTotal.toFixed(2));
我希望帮助
你需要调用'toFixed'上小计为好。 – 2012-07-25 09:20:08
另外值得注意的是,这只是普通的JavaScript而不是jQuery :) – Sphvn 2012-07-25 09:26:14
@Pankar在JavaScript中没有向下转换,因为int和float都是'Number'对象。事情是,即使使用浮动,所有尾随零也被移除。由于这个限制'toFixed'返回'String',而不是'Number'。 – 2012-07-25 09:58:17