【问题标题】:How can I get NumberFormat to use a currency but with fractional cents/pennies?如何让 NumberFormat 使用一种货币,但使用分数美分/美分?
【发布时间】:2018-12-03 20:07:53
【问题描述】:

我想使用NumberFormatDouble 转换为String。我目前正在使用基于货币区域设置的NumberFormat,但这会将Double 舍入到小数点后两位。我怎样才能让它不四舍五入货币,以便它包括小数便士?

如果我有

val doubleFormatMoney = 1.032323135

val format = NumberFormat.getCurrencyInstance(Locale.US)

val stringFormatMoney = format.format(doubleFormatMoney)

那么我们应该有stringFormatMoney = $1.032323135,但我得到的是stringFormatMoney = $1.03

【问题讨论】:

  • 为什么不包括适用的代码?这样会更容易回答。
  • System.out.println("" + new Double(1d/3d));
  • 注意,首先不应该使用 Double 来处理货币值,请参阅javapractices.com/topic/TopicAction.do?Id=213
  • 美国货币四舍五入到小数点后两位,因此您的货币采用这种格式。如果您不想更改您的号码,而只想在您的号码前面添加一个货币符号,那么您为什么不创建一个方法来做到这一点呢?

标签: java scala format currency number-formatting


【解决方案1】:

每个区域设置的货币格式规范包括要使用的小数位数,因为这因货币而异(某些货币使用 3dp,例如约旦第纳尔)。因此NumberFormat.getCurrencyInstance(Locale.US) 包括根据定义舍入到 2dp。

如果你想使用标准的DoubletoString加上Locale的货币符号,你可以这样做:

Currency.getInstance(Locale.US).getSymbol(Locale.US) + doubleFormatMoney

How to get the currency symbol for particular country using locale?

【讨论】:

    猜你喜欢
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多