使用 toLocaleString 为负值在括号中显示数字
Display number in brackets using toLocaleString for negative values
我一直在尝试根据国家/地区更改 AngularJS 应用程序中的数字,并使用以下功能
在整个应用程序中使用 .toLocaleString
功能
numberValueTransformation(value) {
if (value === 0 || value === undefined) {
return 0;
}
const currencyLocale = this.UserPreferences.getCountryLocale().replace(/fr-FR/g, 'de-DE');
const currencyCode = this.UserPreferences.getCountryCode();
return Number(value).toLocaleString(currencyLocale, {
// style: 'currency',
currency: currencyCode,
minimumFractionDigits: 2
});
}
上述函数工作得很好,但我需要在整个应用程序的括号中显示负值。我们可以修改 .toLocaleString
以获得括号中的负值,还是我需要手动更改整个应用程序?
我得到的值为 123456689 美元。但是,如果我得到负值 -$123456789,但在这里我想要的值为 ($123456789) <--- 括号代表减号。
您可以自己连接检查,而不是直接返回结果。对正数进行转换,如果原始值小于 0,则用括号括起来。:
var absValue = Math.abs(value);
var returnString = Number(absValue).toLocaleString(currencyLocale, {
// style: 'currency',
currency: currencyCode,
minimumFractionDigits: 2
});
return value < 0 ? '(' + returnString + ')' : returnString;
为此,可以查看 numbro.js 库 https://numbrojs.com/ 有一个功能可以根据要求在括号中格式化负值。代码会像这样工作
console.log(
numbro(-123456.78).formatCurrency({
thousandSeparated: true,
mantissa: 2,
negative: "parenthesis" // This does what you want
}))
<script src="https://cdn.jsdelivr.net/npm/numbro@2.3.1/dist/numbro.min.js"></script>
还有很多其他格式选项,请参阅 https://numbrojs.com/format.html#currency
我一直在尝试根据国家/地区更改 AngularJS 应用程序中的数字,并使用以下功能
在整个应用程序中使用.toLocaleString
功能
numberValueTransformation(value) {
if (value === 0 || value === undefined) {
return 0;
}
const currencyLocale = this.UserPreferences.getCountryLocale().replace(/fr-FR/g, 'de-DE');
const currencyCode = this.UserPreferences.getCountryCode();
return Number(value).toLocaleString(currencyLocale, {
// style: 'currency',
currency: currencyCode,
minimumFractionDigits: 2
});
}
上述函数工作得很好,但我需要在整个应用程序的括号中显示负值。我们可以修改 .toLocaleString
以获得括号中的负值,还是我需要手动更改整个应用程序?
我得到的值为 123456689 美元。但是,如果我得到负值 -$123456789,但在这里我想要的值为 ($123456789) <--- 括号代表减号。
您可以自己连接检查,而不是直接返回结果。对正数进行转换,如果原始值小于 0,则用括号括起来。:
var absValue = Math.abs(value);
var returnString = Number(absValue).toLocaleString(currencyLocale, {
// style: 'currency',
currency: currencyCode,
minimumFractionDigits: 2
});
return value < 0 ? '(' + returnString + ')' : returnString;
为此,可以查看 numbro.js 库 https://numbrojs.com/ 有一个功能可以根据要求在括号中格式化负值。代码会像这样工作
console.log(
numbro(-123456.78).formatCurrency({
thousandSeparated: true,
mantissa: 2,
negative: "parenthesis" // This does what you want
}))
<script src="https://cdn.jsdelivr.net/npm/numbro@2.3.1/dist/numbro.min.js"></script>