2014-05-06 23 views
2

我的HTML如何將價格限制在2個小數點

<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

+0

http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in- javascript – Aheinlein

+1

不適合你的谷歌? –

+3

OP已經使用toFixed,它只是在錯誤的地方,所以它不是真的重複。 – adeneo

回答

6

只是移動toFixed乘法的輸出,而不是。

.val((Number(price) * quantity).toFixed(2)); 
+0

謝謝!我不完全確定它爲什麼不起作用。 – Zinox

+0

你能告訴我爲什麼這個--- Number($(「input [name = order-total]」).val(sum)).toFixed(2); ---不工作,預先感謝 – Zinox

+1

它不工作,因爲'val(sum)'返回jQuery對象,它沒有toFixed方法。你必須轉換傳入的值,如'val(sum.toFixed(2))' – adeneo

1

嘗試這種情況:

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

謝謝,最受讚賞的幫助。 – Zinox

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 

但是,那麼你會想知道如何Precision()不同於toFixed()?那麼,他們是不同的.toFixed()給你一個固定的小數位數,而另一個給你一個固定數量的有效數字。

var iNum = 15.667; 
iNum.toFixed(2);  // Returns "15.67" 
iNum.toPrecision(2); // Returns "16" 
iNum.toPrecision(3); // Returns "15.7" 
+0

非常感謝,感謝您的幫助。 – Zinox

+0

不客氣。 – GTodorov

0

一兩件事你可以做,如果你是有輕微的四捨五入OK(聽起來像你不會是,但還不如給多個建議),是包裝您的結果toFixed

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

但實際上,如果你需要浮點數的精度,你應該看看像bigDecimal.js

+0

謝謝!最受讚賞的幫助。 – Zinox

相關問題