/*decimal_sep: character used as decimal separator, it defaults to '.' when omittedthousands_sep: char used as thousands separator, it defaults to ',' when omitted*/Number.prototype.toMoney = function(decimals, decimal_sep, thousands_sep){var n = this,c = isNaN(decimals) ? 2 : Math.abs(decimals), // If decimal is zero we must take it. It means the user does not want to show any decimald = decimal_sep || '.', // If no decimal separator is passed, we use the dot as default decimal separator (we MUST use a decimal separator)
/*According to [https://stackoverflow.com/questions/411352/how-best-to-determine-if-an-argument-is-not-sent-to-the-javascript-function]the fastest way to check for not defined parameter is to use typeof value === 'undefined'rather than doing value === undefined.*/t = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, // If you don't want to use a thousands separator you can pass empty string as thousands_sep value
sign = (n < 0) ? '-' : '',
// Extracting the absolute value of the integer part of the number and converting to stringi = parseInt(n = Math.abs(n).toFixed(c)) + '',
j = ((j = i.length) > 3) ? j % 3 : 0;return sign + (j ? i.substr(0, j) + t : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : '');}
这里有一些测试:
// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)alert(123456789.67392.toMoney() + '\n' + 123456789.67392.toMoney(3) + '\n' + 123456789.67392.toMoney(0) + '\n' + (123456).toMoney() + '\n' + (123456).toMoney(0) + '\n' + 89.67392.toMoney() + '\n' + (89).toMoney());
// Some tests (do not forget parenthesis when using negative numbers and number with no decimals)alert((-123456789.67392).toMoney() + '\n' + (-123456789.67392).toMoney(-3));
function getMoney(A){var a = new Number(A);var b = a.toFixed(2); // Get 12345678.90a = parseInt(a); // Get 12345678b = (b-a).toPrecision(2); // Get 0.90b = parseFloat(b).toFixed(2); // In case we get 0.0, we pad it out to 0.00a = a.toLocaleString(); // Put in commas - Internet Explorer also puts in .00, so we'll get 12,345,678.00// If Internet Explorer (our number ends in .00)if(a < 1 && a.lastIndexOf('.00') == (a.length - 3)){a = a.substr(0, a.length-3); // Delete the .00}return a + b.substr(1); // Remove the 0 from b, then return a + b = 12,345,678.90}alert(getMoney(12345678.9));
String.prototype.reverse = function() {return this.split('').reverse().join('');};
Number.prototype.toCurrency = function( round_decimal /*boolean*/ ) {// format decimal or round to nearest integervar n = this.toFixed( round_decimal ? 0 : 2 );
// convert to a string, add commas every 3 digits from left to right// by reversing stringreturn (n + '').reverse().replace( /(\d{3})(?=\d)/g, '$1,' ).reverse();};
// Create our number formatter.const formatter = new Intl.NumberFormat('en-US', {style: 'currency',currency: 'USD',
// These options are needed to round to whole numbers if that's what you want.//minimumFractionDigits: 0, // (this suffices for whole numbers, but will print 2500.10 as $2,500.1)//maximumFractionDigits: 0, // (causes 2500.99 to be printed as $2,501)});
console.log(formatter.format(2500)); /* $2,500.00 */
var decimalCharacter = Number("1.1").toLocaleString().substr(1,1);var defaultCurrencyMarker = "$";function formatCurrency(number, currencyMarker) {if (typeof number != "number")number = parseFloat(number, 10);
// if NaN is passed in or comes from the parseFloat, set it to 0.if (isNaN(number))number = 0;
var sign = number < 0 ? "-" : "";number = Math.abs(number); // so our signage goes before the $ symbol.
var integral = Math.floor(number);var formattedIntegral = integral.toLocaleString();
// IE returns "##.00" while others return "##"formattedIntegral = formattedIntegral.split(decimalCharacter)[0];
var decimal = Math.round((number - integral) * 100);return sign + (currencyMarker || defaultCurrencyMarker) +formattedIntegral +decimalCharacter +decimal.toString() + (decimal < 10 ? "0" : "");}
function benchmark(f) {var start = new Date().getTime();f();return new Date().getTime() - start;}
function benchmark_format(f) {console.log(f);time = benchmark(function () {for (var i = 0; i < 100000; i++) {f.call(123456789, 0);f.call(123456789, 2);}});console.log(time.format(0) + 'ms');}
// If not using async, the browser will stop responding while running.// This will create a new thread to benchmarkasync = [];function next() {setTimeout(function () {f = async.shift();f && f();next();}, 10);}
console.log('======== Benchmark ========');async.push(function () { benchmark_format(Number.prototype.format); });next();
// var formatter = Format_Numb( "%m €");// simple example for Euro...
// but we use a complex example:
var formatter = Format_Numb("a%%%3mxx \"zz\"%8.2f°\" >0x%8X<");
// formatter is now a function, which can be used more than once (this is an example, that can be tested:)
var v1 = formatter(1897654.8198344);
var v2 = formatter(4.2);
... (and thousands of rows)
var formatMoney = function (value) {// Convert the value to a floating point number in case it arrives as a string.var numeric = parseFloat(value);// Specify the local currency.return numeric.toLocaleString('USD', { style: 'currency', currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 2 });}
// Default usage:accounting.formatMoney(12345678); // $12,345,678.00
// European formatting (custom symbol and separators), can also use options object as second parameter:accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
// Negative values can be formatted nicely:accounting.formatMoney(-500000, "£ ", 0); // £ -500,000
// Simple `format` string allows control of symbol position (%v = value, %s = symbol):accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP
// Euro currency symbol to the rightaccounting.formatMoney(5318008, {symbol: "€", precision: 2, thousand: ".", decimal : ",", format: "%v%s"}); // 1.008,00€
<tr><td><label class="control-label">Number Field:</label><div class="inner-addon right-addon"><input type="text" id="numberField"name="numberField"class="form-control"autocomplete="off"maxlength="17"data-rule-required="true"data-msg-required="Cannot be blank."data-msg-maxlength="Exceeding the maximum limit of 13 digits. Example: 1234567890123"data-rule-numberExceedsMaxLimit="en"data-msg-numberExceedsMaxLimit="Exceeding the maximum limit of 13 digits. Example: 1234567890123"onkeydown="return isNumber(event, 'en')"onkeyup="return updateField(this)"onblur="numberFormatter(this,'en','Invalid character(s) found. Please enter valid characters.')"></div></td></tr>
<tr><td><label class="control-label">Decimal Field:</label><div class="inner-addon right-addon"><input type="text" id="decimalField"name="decimalField"class="form-control"autocomplete="off"maxlength="20"data-rule-required="true"data-msg-required="Cannot be blank."data-msg-maxlength="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"data-rule-decimalExceedsMaxLimit="en"data-msg-decimalExceedsMaxLimit="Exceeding the maximum limit of 16 digits. Example: 1234567890123.00"onkeydown="return isDecimal(event, 'en')"onkeyup="return updateField(this)"onblur="decimalFormatter(this,'en','Invalid character(s) found. Please enter valid characters.')"></div></td></tr>