2016-07-12 74 views
-1

如何四捨五入錢數到小數點後兩位使用JQuery的錢/貨幣四捨五入到2位小數

167,7451四捨五入爲167,75

12,1819784算術慣例被四捨五入到12,18

注意我想這樣做,並返回一個浮點數,而不是一個字符串,所以簡單的格式化解決方案不是我正在尋找的。

到目前爲止,我發現:

amount = 167.7451; 
rounded = (amount.toFixed(2)); 
alert(rounded); 

然而toFixed()的結果是一個字符串,所以如果我需要做更多的計算我需要重新解析字符串爲float。

的.toPrecision方法,而不是想知道我有多少位需要這麼圓我需要的金額小數點後兩位:這是荒謬的

amount = 167.7451; 
alert(amount.toPrecision(5)); 

,因爲我需要先知道有多少位我有小數前。

+0

'167,7451四捨五入爲167,75'沒有小數...... –

+0

'167,75'這甚至不是一個有效的數字,以逗號開頭,當你有幾百個而不是幾十個時。或者你錯字'''而不是'.'? – guradio

+0

在這裏回答:http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-in-javascript – janar2005

回答

-1
167.7451 is rounded to <span class="result1"></span> 
<br>By adding 10 result is: <span class="result2"></span> 
<br>By adding rounded 0.254999 result is: <span class="result3"></span> 

<script type="text/javascript"> 
    window.jQuery(document).ready(function($){ 
     function my_round(num) { 
      return Math.round(num * 10 * 10)/100; 
     } 

     var amount = 167.7451, 
      amount1 = my_round(amount), 
      amount2 = amount1 + 10, 
      amount3 = amount2 + my_round(0.254999); 


     window.jQuery('.result1').text(amount1); 
     window.jQuery('.result2').text(amount2); 
     window.jQuery('.result3').text(amount3); 
    }); 
</script> 

更新代碼應工作。

+0

解決方法是錯誤的,如果你輸入156893.145並且它取得156893.14而不是156893.15 !!! –