简体   繁体   English

如何使用 Java 或 Groovy printf 将千位分隔符添加到字符串

[英]How to use Java or Groovy printf to add Thousands separator to String

In Java, I need to add a thousands separator to a decimal number formatted as a String .在 Java 中,我需要向格式化为String的十进制数添加千位分隔符。 However, I do not want a millions or billions separator... just a thousands separator with the existing fractional part of the number preserved.但是,我想要百万或十亿分隔符……只是保留数字的现有小数部分的千位分隔符。

9 == 9 9 == 9

999.999 == 999.999 999.999 == 999.999

9,999 == 9999 9,999 == 9999

999999,999.999 == 999999999.999 999999,999.999 == 999999999.999

I do not strictly need to use printf, but the conversion must be as fast as possible.我并不严格需要使用 printf,但转换必须尽可能快。

The input and output type must both be String .输入和输出类型都必须是String

Thanks!谢谢!

Firstly, this issue is not as simple as it appears since the thousand separator is not always a comma and is dependant on the user's Locale.首先,这个问题并不像看起来那么简单,因为千位分隔符并不总是逗号并且取决于用户的语言环境。 In some cases it is actually a period, which may cause problems with any code you write for String manipulation.在某些情况下,它实际上是一个句点,这可能会导致您为字符串操作编写的任何代码出现问题。

If you wish to honour the user's Locale then a more considered approach is required, on the other hand, if you just want to take account of this one specific case and don't care about Locale settings then you could try something like this:如果您希望尊重用户的语言环境,则需要更深思熟虑的方法,另一方面,如果您只想考虑这个特定情况而不关心语言环境设置,那么您可以尝试以下方法:

String s = "99999999.999";
s.replaceFirst("^(\\d+)(\\d{3})(\\.|$)", "$1,$2$3");

The best solution so far is:目前最好的解决办法是:

return text.replaceFirst("^(\\d+)(\\d{3})(\\.|$)", "$1,$2$3"); return text.replaceFirst("^(\\d+)(\\d{3})(\\.|$)", "$1,$2$3");

java.text.NumberFormat is what you need. java.text.NumberFormat 正是您所需要的。

Visit https://docs.oracle.com/javase/1.5.0/docs/api/java/text/NumberFormat.html .访问https://docs.oracle.com/javase/1.5.0/docs/api/java/text/NumberFormat.html

def test='6816843541.5432'
index = test.indexOf('.')
test = test.substring(0,index - 3 ) + ',' + test.substring(index-3,test.size())
println test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM