यहाँ एक कुछ कोड मैं एक लंबे समय पहले लिखा था अल्पविरामों से एक नंबर फ़ॉर्मेट करने के लिए है। एक उदाहरण 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)" />
वह नंबर करने के लिए अल्पविराम जोड़ सकते हैं और मोर्चे पर डॉलर चिन्ह तमाचा होगा।
स्रोत
2009-07-22 02:20:09
धन्यवाद, जॉन। मैंने मुद्रा पद्धति के लिए फ्लाई स्वरूपण प्राप्त करने के लिए इस विधि का उपयोग किया। भी पढ़ने के लिए बहुत आसान है! +1 –
-1 इसमें एक बग है और 99 99 में समाप्त होने वाली संख्याओं के साथ काम नहीं करता है, उदाहरण के लिए "1879.9 999" प्रारूप 1,879.10 (!) –
के रूप में यह एक बग नहीं है, जो डिज़ाइन द्वारा है। यदि आपने दशमलव स्थान को 4 पर सेट किया था, तो आपके पास ".9999" था। – emrahgunduz