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 print开发者_Python百科f, 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");
def test='6816843541.5432'
index = test.indexOf('.')
test = test.substring(0,index - 3 ) + ',' + test.substring(index-3,test.size())
println test
java.text.NumberFormat is what you need.
Visit https://docs.oracle.com/javase/1.5.0/docs/api/java/text/NumberFormat.html.
精彩评论