2009-07-22 115 views
6

我有一系列texfields,我想将其格式化为货币。优选地,这将在飞行中完成,但至少在onblur上完成。我的货币格式是349507 - > 349,507美元。可能吗?如何格式化输入到HTML文本字段中的文本(如货币)?

我更喜欢HTML/CSS/JS解决方案,因为我需要更少的解释。我对jQuery并不熟悉。

任何帮助,非常感谢。
Mike

回答

5

第一个结果在谷歌搜索 “的javascript格式货币”

http://www.web-source.net/web_development/currency_formatting.htm

function CurrencyFormatted(amount) 
{ 
    var i = parseFloat(amount); 
    if(isNaN(i)) { i = 0.00; } 
    var minus = ''; 
    if(i < 0) { minus = '-'; } 
    i = Math.abs(i); 
    i = parseInt((i + .005) * 100); 
    i = i/100; 
    s = new String(i); 
    if(s.indexOf('.') < 0) { s += '.00'; } 
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; } 
    s = minus + s; 
    return s; 
} 
11

下面是我写了很久以前用逗号格式化数字的一些代码。一个例子是formatNumber(349507, 0, 2, true)"349,507.00"

// Reformats a number by inserting commas and padding out the number of digits 
// and decimal places. 
// 
// Parameters: 
//  number:  The number to format. All non-numeric characters are 
//     stripped out first. 
//  digits:  The minimum number of digits to the left of the decimal 
//     point. The extra places are padded with zeros. 
//  decimalPlaces: The number of places after the decimal point, or zero to 
//     omit the decimal point. 
//  withCommas: True to insert commas every 3 places, false to omit them. 
function formatNumber(number, digits, decimalPlaces, withCommas) 
{ 
     number  = number.toString(); 
    var simpleNumber = ''; 

    // Strips out the dollar sign and commas. 
    for (var i = 0; i < number.length; ++i) 
    { 
     if (".".indexOf(number.charAt(i)) >= 0) 
      simpleNumber += number.charAt(i); 
    } 

    number = parseFloat(simpleNumber); 

    if (isNaN(number))  number  = 0; 
    if (withCommas == null) withCommas = false; 
    if (digits  == 0) digits  = 1; 

    var integerPart = (decimalPlaces > 0 ? Math.floor(number) : Math.round(number)); 
    var string  = ""; 

    for (var i = 0; i < digits || integerPart > 0; ++i) 
    { 
     // Insert a comma every three digits. 
     if (withCommas && string.match(/^\d\d\d/)) 
      string = "," + string; 

     string  = (integerPart % 10) + string; 
     integerPart = Math.floor(integerPart/10); 
    } 

    if (decimalPlaces > 0) 
    { 
     number -= Math.floor(number); 
     number *= Math.pow(10, decimalPlaces); 

     string += "." + formatNumber(number, decimalPlaces, 0); 
    } 

    return string; 
} 

您可以使用它在一个onblur事件处理程序,像这样:

<input type="text" onblur="this.value = '$' + formatNumber(this.value, 0, 0, true)" /> 

这将添加逗号的数量和拍打着前一个美元符号。

+0

谢谢你,约翰。我在应用程序中使用这种方法来为货币字段快速格式化。非常容易阅读! +1 – 2010-02-23 21:54:21