2011-05-25 97 views
3

我有一个由2个变量格式为货币在Javascript

var EstimatedTotal = GetNumeric(ServiceLevel) * GetNumeric(EstimatedCoreHours); 

是否有可能,和乘法的变量,如果因此如何,或者什么是所谓的格式化这个货币的功能?我一直在谷歌搜索,只能找到一个函数,我见过的唯一方法是真的很长啰嗦

+0

http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript – goodeye 2012-12-05 03:03:31

回答

7

从这里取:http://javascript.internet.com/forms/currency-format.html。我已经使用它,它运作良好。

function formatCurrency(num) 
{ 
    num = num.toString().replace(/\$|\,/g, ''); 
    if (isNaN(num)) 
    { 
     num = "0"; 
    } 

    sign = (num == (num = Math.abs(num))); 
    num = Math.floor(num * 100 + 0.50000000001); 
    cents = num % 100; 
    num = Math.floor(num/100).toString(); 

    if (cents < 10) 
    { 
     cents = "0" + cents; 
    } 
    for (var i = 0; i < Math.floor((num.length - (1 + i))/3); i++) 
    { 
     num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3)); 
    } 

    return (((sign) ? '' : '-') + '$' + num + '.' + cents); 
} 
+1

的可能的复制静默-1上没有交代工作代码? – 2011-06-11 14:59:06

7

如果你正在寻找一个快速的功能,将格式化您的编号(例如:1234.5678)喜欢的东西:$ 1234.57,你可以使用.toFixed(..)方法:

EstimatedTotal = "$" + EstimatedTotal.toFixed(2); 

的toFixed函数将一个整数值作为参数,这意味着尾随小数的数量。有关此方法的更多信息,请参见http://www.w3schools.com/jsref/jsref_tofixed.asp

否则,如果您希望将输出格式设置为:$ 1,234.57,则需要为此实现自己的功能。下面是与实施两个环节:

1

可能不完美,但适合我。

if (String.prototype.ToCurrencyFormat == null) 
    String.prototype.ToCurrencyFormat = function() 
    { 
     if (isNaN(this * 1) == false) 
      return "$" + (this * 1).toFixed(2); 
    }