我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
我想用JavaScript格式化价格。我想要一个函数,它将浮点作为参数,并返回如下格式的字符串:
"$ 2,500.00"
我该怎么做?
当前回答
javascript数字格式化程序(以前在Google Code)
短、快、灵活但独立。接受标准数字格式,如#、##0.00或带否定的-000.####。接受任何国家/地区格式,如###0,00,#,###.##,#‘###.##或任何类型的非编号符号。接受任意数字分组。#、##、#0.000或#、####0.##均有效。接受任何冗余/万无一失的格式。##、###、##。#或0#、#00####0#都正常。自动数字舍入。简单的界面,只需提供如下掩码和值:格式(“0.0000”,3.141592)。在掩码中包含前缀和后缀
(摘自自述)
其他回答
此答案符合以下标准:
不依赖于外部依赖项。支持本地化。有测试/证明。使用简单和最佳的编码实践(没有复杂的正则表达式,使用标准的编码模式)。
此代码基于其他答案中的概念。如果这是一个问题的话,它的执行速度应该是最好的。
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" : "");
}
这些测试仅适用于美国语言环境机器。做出这个决定是为了简单,因为这可能会导致糟糕的输入(错误的自动定位),从而导致糟糕的输出问题。
var tests = [
// [ input, expected result ]
[123123, "$123,123.00"], // no decimal
[123123.123, "$123,123.12"], // decimal rounded down
[123123.126, "$123,123.13"], // decimal rounded up
[123123.4, "$123,123.40"], // single decimal
["123123", "$123,123.00"], // repeat subset of the above using string input.
["123123.123", "$123,123.12"],
["123123.126", "$123,123.13"],
[-123, "-$123.00"] // negatives
];
for (var testIndex=0; testIndex < tests.length; testIndex++) {
var test = tests[testIndex];
var formatted = formatCurrency(test[0]);
if (formatted == test[1]) {
console.log("Test passed, \"" + test[0] + "\" resulted in \"" + formatted + "\"");
} else {
console.error("Test failed. Expected \"" + test[1] + "\", got \"" + formatted + "\"");
}
}
请在下面的代码中找到我为支持国际化而开发的内容。
它将给定的数值格式化为特定于语言的格式。在给定的示例中,我使用了“en”,同时测试了“es”、“fr”和其他格式不同的国家。它不仅可以阻止用户键入字符,还可以格式化制表符上的值。
我已经为数字和十进制格式创建了组件。除此之外,我还创建了parseNumber(value,locale)和parseDecimal(value,locale)函数,这些函数将解析格式化数据以用于任何其他业务目的。所述函数将接受格式化数据并返回非格式化值。我在下面的共享代码中使用了jQuery验证器插件。
HTML格式:
<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>
JavaScript:
/*
* @author: dinesh.lomte
*/
/* Holds the maximum limit of digits to be entered in number field. */
var numericMaxLimit = 13;
/* Holds the maximum limit of digits to be entered in decimal field. */
var decimalMaxLimit = 16;
/**
*
* @param {type} value
* @param {type} locale
* @returns {Boolean}
*/
parseDecimal = function(value, locale) {
value = value.trim();
if (isNull(value)) {
return 0.00;
}
if (isNull(locale)) {
return value;
}
if (getNumberFormat(locale)[0] === '.') {
value = value.replace(/\./g, '');
} else {
value = value.replace(
new RegExp(getNumberFormat(locale)[0], 'g'), '');
}
if (getNumberFormat(locale)[1] === ',') {
value = value.replace(
new RegExp(getNumberFormat(locale)[1], 'g'), '.');
}
return value;
};
/**
*
* @param {type} element
* @param {type} locale
* @param {type} nanMessage
* @returns {Boolean}
*/
decimalFormatter = function (element, locale, nanMessage) {
showErrorMessage(element.id, false, null);
if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
return true;
}
var value = element.value.trim();
value = value.replace(/\s/g, '');
value = parseDecimal(value, locale);
var numberFormatObj = new Intl.NumberFormat(locale,
{ minimumFractionDigits: 2,
maximumFractionDigits: 2
}
);
if (numberFormatObj.format(value) === 'NaN') {
showErrorMessage(element.id, true, nanMessage);
setFocus(element.id);
return false;
}
element.value = numberFormatObj.format(value);
return true;
};
/**
*
* @param {type} element
* @param {type} locale
* @param {type} nanMessage
* @returns {Boolean}
*/
numberFormatter = function (element, locale, nanMessage) {
showErrorMessage(element.id, false, null);
if (isNull(element.id) || isNull(element.value) || isNull(locale)) {
return true;
}
var value = element.value.trim();
var format = getNumberFormat(locale);
if (hasDecimal(value, format[1])) {
showErrorMessage(element.id, true, nanMessage);
setFocus(element.id);
return false;
}
value = value.replace(/\s/g, '');
value = parseNumber(value, locale);
var numberFormatObj = new Intl.NumberFormat(locale,
{ minimumFractionDigits: 0,
maximumFractionDigits: 0
}
);
if (numberFormatObj.format(value) === 'NaN') {
showErrorMessage(element.id, true, nanMessage);
setFocus(element.id);
return false;
}
element.value =
numberFormatObj.format(value);
return true;
};
/**
*
* @param {type} id
* @param {type} flag
* @param {type} message
* @returns {undefined}
*/
showErrorMessage = function(id, flag, message) {
if (flag) {
// only add if not added
if ($('#'+id).parent().next('.app-error-message').length === 0) {
var errorTag = '<div class=\'app-error-message\'>' + message + '</div>';
$('#'+id).parent().after(errorTag);
}
} else {
// remove it
$('#'+id).parent().next(".app-error-message").remove();
}
};
/**
*
* @param {type} id
* @returns
*/
setFocus = function(id) {
id = id.trim();
if (isNull(id)) {
return;
}
setTimeout(function() {
document.getElementById(id).focus();
}, 10);
};
/**
*
* @param {type} value
* @param {type} locale
* @returns {Array}
*/
parseNumber = function(value, locale) {
value = value.trim();
if (isNull(value)) {
return 0;
}
if (isNull(locale)) {
return value;
}
if (getNumberFormat(locale)[0] === '.') {
return value.replace(/\./g, '');
}
return value.replace(
new RegExp(getNumberFormat(locale)[0], 'g'), '');
};
/**
*
* @param {type} locale
* @returns {Array}
*/
getNumberFormat = function(locale) {
var format = [];
var numberFormatObj = new Intl.NumberFormat(locale,
{ minimumFractionDigits: 2,
maximumFractionDigits: 2
}
);
var value = numberFormatObj.format('132617.07');
format[0] = value.charAt(3);
format[1] = value.charAt(7);
return format;
};
/**
*
* @param {type} value
* @param {type} fractionFormat
* @returns {Boolean}
*/
hasDecimal = function(value, fractionFormat) {
value = value.trim();
if (isNull(value) || isNull(fractionFormat)) {
return false;
}
if (value.indexOf(fractionFormat) >= 1) {
return true;
}
};
/**
*
* @param {type} event
* @param {type} locale
* @returns {Boolean}
*/
isNumber = function(event, locale) {
var keyCode = event.which ? event.which : event.keyCode;
// Validating if user has pressed shift character
if (keyCode === 16) {
return false;
}
if (isNumberKey(keyCode)) {
return true;
}
var numberFormatter = [32, 110, 188, 190];
if (keyCode === 32
&& isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
return true;
}
if (numberFormatter.indexOf(keyCode) >= 0
&& getNumberFormat(locale)[0] === getFormat(keyCode)) {
return true;
}
return false;
};
/**
*
* @param {type} event
* @param {type} locale
* @returns {Boolean}
*/
isDecimal = function(event, locale) {
var keyCode = event.which ? event.which : event.keyCode;
// Validating if user has pressed shift character
if (keyCode === 16) {
return false;
}
if (isNumberKey(keyCode)) {
return true;
}
var numberFormatter = [32, 110, 188, 190];
if (keyCode === 32
&& isNull(getNumberFormat(locale)[0]) === isNull(getFormat(keyCode))) {
return true;
}
if (numberFormatter.indexOf(keyCode) >= 0
&& (getNumberFormat(locale)[0] === getFormat(keyCode)
|| getNumberFormat(locale)[1] === getFormat(keyCode))) {
return true;
}
return false;
};
/**
*
* @param {type} keyCode
* @returns {Boolean}
*/
isNumberKey = function(keyCode) {
if ((keyCode >= 48 && keyCode <= 57) ||
(keyCode >= 96 && keyCode <= 105)) {
return true;
}
var keys = [8, 9, 13, 35, 36, 37, 39, 45, 46, 109, 144, 173, 189];
if (keys.indexOf(keyCode) !== -1) {
return true;
}
return false;
};
/**
*
* @param {type} keyCode
* @returns {JSON@call;parse.numberFormatter.value|String}
*/
getFormat = function(keyCode) {
var jsonString = '{"numberFormatter" : [{"key":"32", "value":" ", "description":"space"}, {"key":"188", "value":",", "description":"comma"}, {"key":"190", "value":".", "description":"dot"}, {"key":"110", "value":".", "description":"dot"}]}';
var jsonObject = JSON.parse(jsonString);
for (var key in jsonObject.numberFormatter) {
if (jsonObject.numberFormatter.hasOwnProperty(key)
&& keyCode === parseInt(jsonObject.numberFormatter[key].key)) {
return jsonObject.numberFormatter[key].value;
}
}
return '';
};
/**
*
* @type String
*/
var jsonString = '{"shiftCharacterNumberMap" : [{"char":")", "number":"0"}, {"char":"!", "number":"1"}, {"char":"@", "number":"2"}, {"char":"#", "number":"3"}, {"char":"$", "number":"4"}, {"char":"%", "number":"5"}, {"char":"^", "number":"6"}, {"char":"&", "number":"7"}, {"char":"*", "number":"8"}, {"char":"(", "number":"9"}]}';
/**
*
* @param {type} value
* @returns {JSON@call;parse.shiftCharacterNumberMap.number|String}
*/
getShiftCharSpecificNumber = function(value) {
var jsonObject = JSON.parse(jsonString);
for (var key in jsonObject.shiftCharacterNumberMap) {
if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
&& value === jsonObject.shiftCharacterNumberMap[key].char) {
return jsonObject.shiftCharacterNumberMap[key].number;
}
}
return '';
};
/**
*
* @param {type} value
* @returns {Boolean}
*/
isShiftSpecificChar = function(value) {
var jsonObject = JSON.parse(jsonString);
for (var key in jsonObject.shiftCharacterNumberMap) {
if (jsonObject.shiftCharacterNumberMap.hasOwnProperty(key)
&& value === jsonObject.shiftCharacterNumberMap[key].char) {
return true;
}
}
return false;
};
/**
*
* @param {type} element
* @returns {undefined}
*/
updateField = function(element) {
var value = element.value;
for (var index = 0; index < value.length; index++) {
if (!isShiftSpecificChar(value.charAt(index))) {
continue;
}
element.value = value.replace(
value.charAt(index),
getShiftCharSpecificNumber(value.charAt(index)));
}
};
/**
*
* @param {type} value
* @param {type} element
* @param {type} params
*/
jQuery.validator.addMethod('numberExceedsMaxLimit', function(value, element, params) {
value = parseInt(parseNumber(value, params));
if (value.toString().length > numericMaxLimit) {
showErrorMessage(element.id, false, null);
setFocus(element.id);
return false;
}
return true;
}, 'Exceeding the maximum limit of 13 digits. Example: 1234567890123.');
/**
*
* @param {type} value
* @param {type} element
* @param {type} params
*/
jQuery.validator.addMethod('decimalExceedsMaxLimit', function(value, element, params) {
value = parseFloat(parseDecimal(value, params)).toFixed(2);
if (value.toString().substring(
0, value.toString().lastIndexOf('.')).length > numericMaxLimit
|| value.toString().length > decimalMaxLimit) {
showErrorMessage(element.id, false, null);
setFocus(element.id);
return false;
}
return true;
}, 'Exceeding the maximum limit of 16 digits. Example: 1234567890123.00.');
/**
* @param {type} id
* @param {type} locale
* @returns {boolean}
*/
isNumberExceedMaxLimit = function(id, locale) {
var value = parseInt(parseNumber(
document.getElementById(id).value, locale));
if (value.toString().length > numericMaxLimit) {
setFocus(id);
return true;
}
return false;
};
/**
* @param {type} id
* @param {type} locale
* @returns {boolean}
*/
isDecimalExceedsMaxLimit = function(id, locale) {
var value = parseFloat(parseDecimal(
document.getElementById(id).value, locale)).toFixed(2);
if (value.toString().substring(
0, value.toString().lastIndexOf('.')).length > numericMaxLimit
|| value.toString().length > decimalMaxLimit) {
setFocus(id);
return true;
}
return false;
};
这是我的。。。
function thousandCommas(num) {
num = num.toString().split('.');
var ints = num[0].split('').reverse();
for (var out=[],len=ints.length,i=0; i < len; i++) {
if (i > 0 && (i % 3) === 0) out.push(',');
out.push(ints[i]);
}
out = out.reverse() && out.join('');
if (num.length === 2) out += '.' + num[1];
return out;
}
PHP函数“number_format”有一个JavaScript端口。
我发现它非常有用,因为它易于使用,并且对PHP开发人员来说是可识别的。
function number_format (number, decimals, dec_point, thousands_sep) {
var n = number, prec = decimals;
var toFixedFix = function (n,prec) {
var k = Math.pow(10,prec);
return (Math.round(n*k)/k).toString();
};
n = !isFinite(+n) ? 0 : +n;
prec = !isFinite(+prec) ? 0 : Math.abs(prec);
var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec);
// Fix for Internet Explorer parseFloat(0.55).toFixed(0) = 0;
var abs = toFixedFix(Math.abs(n), prec);
var _, i;
if (abs >= 1000) {
_ = abs.split(/\D/);
i = _[0].length % 3 || 3;
_[0] = s.slice(0,i + (n < 0)) +
_[0].slice(i).replace(/(\d{3})/g, sep+'$1');
s = _.join(dec);
} else {
s = s.replace('.', dec);
}
var decPos = s.indexOf(dec);
if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
}
else if (prec >= 1 && decPos === -1) {
s += dec+new Array(prec).join(0)+'0';
}
return s;
}
(原文注释栏,包括以下示例和到期信用)
// Formats a number with grouped thousands
//
// version: 906.1806
// discuss at: http://phpjs.org/functions/number_format
// + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfix by: Michael White (http://getsprink.com)
// + bugfix by: Benjamin Lupton
// + bugfix by: Allan Jensen (http://www.winternet.no)
// + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
// + bugfix by: Howard Yeend
// + revised by: Luke Smith (http://lucassmith.name)
// + bugfix by: Diogo Resende
// + bugfix by: Rival
// + input by: Kheang Hok Chin (http://www.distantia.ca/)
// + improved by: davook
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Jay Klehr
// + improved by: Brett Zamir (http://brett-zamir.me)
// + input by: Amir Habibi (http://www.residence-mixte.com/)
// + bugfix by: Brett Zamir (http://brett-zamir.me)
// * example 1: number_format(1234.56);
// * returns 1: '1,235'
// * example 2: number_format(1234.56, 2, ',', ' ');
// * returns 2: '1 234,56'
// * example 3: number_format(1234.5678, 2, '.', '');
// * returns 3: '1234.57'
// * example 4: number_format(67, 2, ',', '.');
// * returns 4: '67,00'
// * example 5: number_format(1000);
// * returns 5: '1,000'
// * example 6: number_format(67.311, 2);
// * returns 6: '67.31'
// * example 7: number_format(1000.55, 1);
// * returns 7: '1,000.6'
// * example 8: number_format(67000, 5, ',', '.');
// * returns 8: '67.000,00000'
// * example 9: number_format(0.9, 0);
// * returns 9: '1'
// * example 10: number_format('1.20', 2);
// * returns 10: '1.20'
// * example 11: number_format('1.20', 4);
// * returns 11: '1.2000'
// * example 12: number_format('1.2000', 3);
// * returns 12: '1.200'
JavaScript中有一个内置函数toFixed:
var num = new Number(349);
document.write("$" + num.toFixed(2));