简体   繁体   中英

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 . 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

999.999 == 999.999

9,999 == 9999

999999,999.999 == 999999999.999

I do not strictly need to use printf, but the conversion must be as fast as possible.

The input and output type must both be 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");

java.text.NumberFormat is what you need.

Visit 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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