在 Scala Java Play 框架中格式化没有小数的双精度数并为千位添加逗号

Format a double without decimals & adding commas for thousands in Scala Java Play framework

我有双打,例如:

87654783927493.00

23648.00

我想将它们输出为:

87,654,783,927,493

23,648


我找到了以下解决方案:

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

这是在以下人员的帮助下完成的:

how to format a number/date in play 2.0 template?

What is the proper way to format a double in a Play 2 template


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

%,.2f 中的“2”表示格式中使用的小数位数。您可以只使用 %,.0f 代替:

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

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

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

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

使用 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: %s\n",dformatter.format(deciNum))
printf("floatNum: %s\n",fformatter.format(floatNum))

输出为:

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

最好通过简单的例子来理解,使用%,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