2009-07-22 7 views
6

私は通貨としてフォーマットしたい一連のtexfieldを持っています。好ましくは、これはオンザフライで行われるが、少なくともオンブラッブルで行われる。私が通貨フォーマットを意味するものは349507 - > $ 349,507です。出来ますか?通貨のようにHTMLテキストフィールドに入力されたテキストをどのように書式設定できますか?

私は、HTML/CSS/JSソリューションを好む理由は、説明が少なくて済むからです。私はjQueryに慣れていません。

ご協力いただきまして誠にありがとうございます。
マイク

答えて

5

まず結果

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"です。数にカンマを追加して、前面にドル記号を平手打ちます

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

:あなたがそうのようなonblurイベントハンドラにそれを使用することができ

// 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; 
} 

。 "JavaScriptの書式通貨" のGoogle検索で

+0

http://www.web-source.net/web_development/currency_formatting.htmは、ジョン、ありがとうございました。私はアプリケーションでこのメソッドを使用して、通貨フィールドのフライ・フォーマットを取得しました。非常に読みやすい! +1 –

+0

-1バグがあり、数字が.9999で終わると動作しません。例えば、 "1879.9999"のような形式は1,879.10です。(!) –

+0

これは設計上のバグではありません。 decimalPlacesを4に設定していた場合は、 ".9999"でした。 – emrahgunduz

関連する問題