• Post Reply Bookmark Topic Watch Topic
  • New Topic

Remove leading zeros up to "0.xx"  RSS feed

 
Thomas Kennedy
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Given a String like "000864.50", how can I strip off the leading zeros except if it's the last character before the decimal? The strings will always end in a decimal place and two digits.

So:

000756.90 becomes 756.90, and 0000070.50 should become 70.50

It seems like I want to do two things:
1. replace all instances of "00." with "0.", recursively, in case it's all leading zeros, and
2. remove all zeros that occur before a pattern that begins with a non-zero digit and ends with a decimal
 
Don Redd
Ranch Hand
Posts: 82
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System.out.println(String.format("%.2f",Float.valueOf("000001.20")));
 
Thomas Kennedy
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you!
 
fred rosenberger
lowercase baba
Bartender
Posts: 12559
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't see how that removes them from the string. All that does is use a format mask to print the string without them...but they are still there.
 
Paul Clapham
Sheriff
Posts: 22704
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, String is immutable so you can't change it in any way. So what's really needed is a way of producing a new string with the desired characteristics. And that's what Don Redd's code does (I suppose -- haven't checked it). Of course in real life you would assign the result of that expression to a variable rather than just printing it, which wasn't what was asked for.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12559
49
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I get all that...

My veiled point was that the solution given didn't really solve the problem as stated...The OP really needs to clarify what they want, if nothing else as an exercise in writing clear specs.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!