-2

Let's say I have a String variable that looks like this. String milli = "2728462" is there a way to convert it to look something like this 2,252,251 which I guess I want as a long.

The thing is it will be passing strings in this format 1512 52 15010 1622274628

and I want it to place the , character where it needs, so if the number is 1000 then place it like so 1,000 and 100000 then 100,000 etc.

How do I properly convert a String variable like that?

Because this

String s="9990449935";  
long l=Long.parseLong(s);  
System.out.println(l);  

Will output 9990449935 and not 9,990,449,935

Mark Denom
  • 987
  • 1
  • 8
  • 24

2 Answers2

2

Basic strategy for is to convert string representation of the number to the one of Number format. Then you have following options to represent this number according to the give Locale.

String.format()

System.out.format(Locale.US, "%,d", Long.parseLong("2728462"));

NumberFormat

System.out.println(NumberFormat.getNumberInstance(Locale.US).format(Long.parseLong("2728462")));
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
  • Oh wow! Thank you! :-) – Mark Denom Feb 11 '19 at 17:59
  • 1
    @MarkDenom - The relevant knowledge is - you should convert the String to some kind of Number, then use the normal number formatting methods to get the output you want. Good answer oleg, but I think more explanation will help future readers. – Stephen P Feb 11 '19 at 18:07
  • By the way, System.out.format() is a synonym of the perhaps more familiar System.out.printf(). String.format() can be used instead of System.out.format() if you want the output to be written to a string instead of printed. – DodgyCodeException Feb 11 '19 at 18:12
  • This is definitely correct answer, I upvoted it. @Mark Denom you should accept it as the best answer. Just to add something related: method parseLong() throws NumberFormatException if the String isn't valid long. I wrote an Open source library that has a utility that converts Strings to Long, Integer, Float etc that doesn't throw the exception but, if exception occurred it returns a default value and optionally prints the exception into a log. This may be convinient. See the article about the lib: https://www.linkedin.com/pulse/open-source-java-library-some-useful-utilities-michael-gantman/ – Michael Gantman Feb 11 '19 at 18:15
0

You can try

String milli = "2728462"
System.out.println(NumberFormat.getInstance(Locale.US).format(Long.parseLong(milli)));
ferpel
  • 206
  • 3
  • 12