2012-01-06 105 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