2011-05-25 76 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); 
    }