Franz Kafka
Franz Kafka

Reputation: 10831

Remove leading zeros with regex but keep minus-sign

I want to replace leading zeros in java with this expression found on this thread:

s.replaceFirst("^0+(?!$)", "")

But how can I make it work for values like -00.8899?

Upvotes: 3

Views: 2715

Answers (2)

Jim
Jim

Reputation: 3684

Why are you dealing with a numeric value in a string variable?

Java being a strongly-typed language, you would probably have an easier time converting that to a float or double, then doing all the business logic, then finally formatting the output.

Something like:

Double d = Double.parseDouble(s);
double val = d; //mind the auto-boxing/unboxing

//business logic   

//get ready to display to the user
DecimalFormat df = new DecimalFormat("#.0000");
String s = df.format(d);

http://download.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

Upvotes: 5

hsz
hsz

Reputation: 152216

You can try with:

String output = "-00.8899".replace("^(-?)0*", "$1");

Output:

-.8899

Upvotes: 6

Related Questions