2016-01-27 53 views
5

號碼我已經從產品價格下面的輸出數字:圓了小數

<span class="amount">77.08</span> 
<span class="amount">18.18</span> 
<span class="amount">20.25</span> 

我要舍起來總是不管是什麼價格,所以結果在這種情況下將是:

<span class="amount">78</span> 
<span class="amount">19</span> 
<span class="amount">21</span> 

我試着用這個代碼,但它只是刪除了整個數:

jQuery('.amount').each(function() { 
    jQuery(this).html(Math.round(parseFloat(jQuery(this).html()))); 
}); 

任何想法,問題出在哪裏?

回答

9

使用Math.ceil()而不是Math.round()

jQuery(this).html(Math.ceil(parseFloat(jQuery(this).html()))); 

Example fiddle

另外請注意,你可以提供一個功能html()整理代碼一點:

$(this).html(function(i, html) { 
    return Math.ceil(parseFloat(html))); 
}); 
+0

是有可能使用如果'span'具有像這樣的貨幣:'€77.08'? – codemaker

+0

不,因爲在這種情況下'parseFloat()'會返回'NaN'。如果有一個貨幣符號需要將其刪除,請嘗試'parseFloat(html.substr(1));' –