格式化不带小数的双精度,并在Scala Java Play框架中添加数千个逗号



我有双打,例如:

87654783927493.00

23648.00

我想将它们输出为:

87,654,783,927,493

23,648


我找到了以下解决方案:

@("%,.2f".format(myDoubleHere).replace(".00",""))

这是在以下方面的帮助下:

如何在播放 2.0 模板中格式化数字/日期?

在 Play 2 模板中格式化双精度的正确方法是什么


我想用更干净的东西代替这个无耻的解决方案。使用.replace()方法砍掉这些小数真的不好看。

%,.2f中的"2"表示要在格式设置中使用的小数位数。 您可以改用%,.0f

"%,.0f".format(myDoubleHere)  

您可以在此处的文档中阅读有关 Java 格式的更多信息。 您的另一个选项是舍入到Int,然后使用%,d

"%,d".format(math.round(myDoubleHere))

这可能会更好地处理某些边缘情况,具体取决于您的用例(例如 5.9会变得6而不是5)。

最好通过简单的例子来理解,使用 %,d

scala> f"Correctly Formatted output using 'f': ${Int.MaxValue}%,d"
val res30: String = Correctly Formatted output using 'f': 2,147,483,647
scala> s"Incorrectly Formatted output using 's': ${Int.MaxValue}%,d"
val res31: String = Incorrectly Formatted output using 's': 2147483647%,d

使用 Java DecimalFormat

我们有
val df = new java.text.DecimalFormat("###,###");
df: java.text.DecimalFormat = java.text.DecimalFormat@674dc

等等

scala> df.format(87654783927493.00)
res: String = 87,654,783,927,493
scala> df.format(23648.00)
res: String = 23,648

对于整数和浮点数,这在常规 Scala 中对我有用:

// get java number formatters
val dformatter = java.text.NumberFormat.getIntegerInstance
val fformatter = java.text.NumberFormat.getInstance
val deciNum = 987654321
val floatNum = 12345678.01
printf("deciNum: %sn",dformatter.format(deciNum))
printf("floatNum: %sn",fformatter.format(floatNum))

输出为:

deciNum: 987,654,321
floatNum: 12,345,678.01

最新更新