【问题标题】:Display number in brackets using toLocaleString for negative values使用 toLocaleString 在括号中显示数字以表示负值
【发布时间】:2019-02-21 18:49:04
【问题描述】:

我一直在尝试根据国家/地区更改 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)

【问题讨论】:

  • “括号中的负值”是什么意思
  • @RokoC.Buljan 我认为他的意思是括号;即,“(100)”表示-100。
  • 是的,我的意思是一样的!
  • 这些没有内置方法。请参阅How can I format numbers as dollars currency string in JavaScript? 进行一些尝试。
  • 只是出于好奇,何时以及为什么要将负数放入字符串、正数和括号内?

标签: javascript angularjs ecma


【解决方案1】:

您可以自己连接检查,而不是直接返回结果。对正数进行转换,如果原始值小于 0,则用括号括起来。:

var absValue = Math.abs(value);
var returnString = Number(absValue).toLocaleString(currencyLocale, {
    // style: 'currency',
    currency: currencyCode,
    minimumFractionDigits: 2
});

return value < 0 ? '(' + returnString + ')' : returnString;

【讨论】:

  • 这在我需要的时候工作得非常接近,但我需要一个减号在括号外的显示。例如 ** -(123.233.42,99) **
  • 更新了我的答案...只需返回前面的 - 即可。
  • 对于负会计数字,括号已经表示负值。减号是多余的。
【解决方案2】:

为此,请查看 numbro.js 库 https://numbrojs.com/ 有一个功能可以根据要求在括号中格式化负值。代码会这样工作

console.log(
numbro(-123456.78).formatCurrency({
    thousandSeparated: true,
    mantissa: 2,
    negative: "parenthesis" // This does what you want
}))
&lt;script src="https://cdn.jsdelivr.net/npm/numbro@2.3.1/dist/numbro.min.js"&gt;&lt;/script&gt;
还有很多其他格式选项,请参阅https://numbrojs.com/format.html#currency

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多