2

我的 HTML

<div class="product-line">              
                    <a href="#" alt="close" class="btn-close" title="Remove"><img alt="remove" src="img/close.png" /></a>
                    <input class="input-text" name="product-code" type="text" placeholder="Product Code" />
                    <input class="input-text" name="product-quantity" type="text" placeholder="Quantity" />
                    <input class="input-text" name="product-discript" type="text" placeholder="Discription of Product" disabled />
                    <label class="label-sign">&pound;</label>
                    <input class="input-text price" name="product-price" type="text" placeholder="RRP Price" disabled />
                        <br>
</div>

我的 JS 代码行

price = $(this).parent("div.product-line").find("input[name=product-price]").val( Number(price).toFixed(2)  *  quantity )

基本上,如果我将例如 40.2 数量 3 相乘,我会得到类似 120.600000000.... 我如何将其限制为 2 个小数点。

数据通过 JSON(由其他人制作)传入。

我是JS新手

4

4 回答 4

6

只需移至toFixed乘法的输出即可。

.val( ( Number(price) *  quantity ).toFixed(2) );
于 2014-05-06T15:15:42.537 回答
1

尝试这个:

var price = $(this).parent("div.product-line").find("input[name=product-price]").val(( Number(price) * quantity ).toFixed(2));
于 2014-05-06T15:18:25.293 回答
0

先相乘再用固定...

price = $(this).parent("div.product-line").find("input[name=product-price]").val( Number(price)  *  quantity ).toFixed(2)

jQuery四舍五入十进制值

toFixed() 方法将数字转换为字符串,保留指定的小数位数。

var iNum = 12345.6789;
iNum.toFixed();    // Returns "12346": note rounding, no fractional part
iNum.toFixed(1);   // Returns "12345.7": note rounding
iNum.toFixed(6);   // Returns "12345.678900": note added zeros

toPrecision() 方法将数字格式化为指定长度。

var iNum = 5.123456;
iNum.toPrecision();    // Returns 5.123456
iNum.toPrecision(5);   // Returns 5.1235
iNum.toPrecision(2);   // Returns 5.1
iNum.toPrecision(1);   // Returns 5

但是你会想知道 toPrecision() 与 toFixed() 有何不同?好吧,它们是不同的。toFixed() 为您提供固定的小数位数,而另一个为您提供固定数量的有效数字。

var iNum = 15.667;
iNum.toFixed(2);        // Returns "15.67"
iNum.toPrecision(2);    // Returns "16"
iNum.toPrecision(3);    // Returns "15.7"
于 2014-05-06T15:20:21.497 回答
0

如果您可以稍微舍入,您可以做的一件事(听起来您不会,但不妨给出多个建议),就是将您的结果包装在 toFixed

(Number(price) * quantity).toFixed(2)

但是,真的,如果你需要浮点数的精度,你应该研究一下bigDecimal.js

于 2014-05-06T15:21:19.367 回答