3

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?

Community
  • 1
  • 1
Franz Kafka
  • 10,623
  • 20
  • 93
  • 149

2 Answers2

6

You can try with:

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

Output:

-.8899
hsz
  • 148,279
  • 62
  • 259
  • 315
  • Hi..Nice solution. But I also want "+" sign before positive numbers. e.g, Double 0.10 should be +.10 and -0.10 should be -.10 and 1.0 should be +1.Please provide solution for this. – AndiM Jun 19 '15 at 06:33
  • @AndiM Just try with: `^([-+]?)0*` – hsz Jun 19 '15 at 07:24
5

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

Jim
  • 3,476
  • 4
  • 23
  • 33