2012-01-06 94 views
0

情況: 我有我使用這些公式開發一個計算器: // ---數學---插入逗號到號碼對象和輸入文本字段

function national(){ 
     x = Number($('#budget').val()); 
     y = Number($('#percentage').val()); 

     a = x * 2; 
     b = [x*(100/100-(1/y))]*2; 
     c = (x*(1/y))*4; 
     d = (b+c)-a; 
     e = (d/a)*100; 
     f = (b+c); 

     $('#one').text(Math.round(a)); 
     $('#two').text(Math.round(b)); 
     $('#three').text(Math.round(c)); 
     $('#four').text(Math.round(d)); 
     $('#five').text(Math.round(e)); 
     $('#six').text(Math.round(f)); 

     $('#input1').text(Math.round(y)); 
     $('#input2').text(Math.round(x)); 


    } 

我不能更改格式太多,因爲我使用此結構使用var作爲僞數組來提供一個條形圖插件,它以圖形方式描述了我的計算。

我已經使用Math.round行動來消除瘋狂的計算,但我需要添加數字格式輸出。

我用這個正則表達式的插圖我逗號

Number.prototype.format = function (f) { 
    return this.toString().split(/(?=(?:\d{3})+(?:\.|$))/g).join(","); 
// ex $('#one').text(a.format()); 
}; 

,但我不知道如何將正則表達式和Math.round行動......他們一直互相殘殺。

問題: 我需要格式化我的輸出DOM對象和我的文本輸入字段。這甚至是可能的,我的語法根本不合適,任何輸入或可能的解決方案,將不勝感激。

獎勵: 我使用jQuery來執行我的計算正在被傾倒入跨度,如果有一個妥善的解決辦法,我可能不僅包含所述溶液在我的輸出範圍,但我輸入文本字段好?

乾杯。

回答

0

使用此:

Number.prototype.format = function() { 
    return this.toString().replace(/(\d)(?=(\d{3})+$)/g, '$1,'); 
}; 

然後,你可以只調用.format()四捨五入後:

$('#one').text(Math.round(a).format()); 
$('#two').text(Math.round(b).format()); 
$('#three').text(Math.round(c).format()); 
$('#four').text(Math.round(d).format()); 
$('#five').text(Math.round(e).format()); 
$('#six').text(Math.round(f).format()); 

$('#input1').text(Math.round(y).format()); 
$('#input2').text(Math.round(x).format()); 
+0

感謝隊友。我一直試圖沒有效果,但通過改變我的正則表達式的結束爲1美元,並且放棄了.join它完美地工作。 – Swordfish0321 2012-01-06 18:09:34