0

How to remove trailing zero in java for a String

below is my string values,
908.10001
508.1000
405.000
302.0000
15.880

I want the output like
908.10001
508.1
405.0
302.0
15.88

dertkw
  • 7,698
  • 5
  • 37
  • 44
Marjer
  • 1,245
  • 6
  • 20
  • 31

4 Answers4

2

Very simple solution:

String string1 = Double.valueOf("302.1000").toString();  // 302.1
String string2 = Double.valueOf("302.0000").toString();  // 302.0
String string3 = Double.valueOf("302.0010").toString();  // 302.001
Braj
  • 45,615
  • 5
  • 55
  • 73
0

I think String replaceAll method can take a regex in parameter, so it can do what you want. i might look something like this:

String s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
ovie
  • 625
  • 3
  • 18
0

You'll have to address trailing non-zeros too. Try BigDecimal with a scale of 1 and ROUND_HALF_UP rounding (if that works for you):

BigDecimal bd = new BigDecimal("302.0000");
System.out.println(bd.setScale(1,BigDecimal.ROUND_HALF_UP).toString()); //outputs 302.0
Edwin Torres
  • 2,561
  • 1
  • 12
  • 15
0

You could construct a BigDecimal and use stripTrailingZeros().

BigDecimal bd = new BigDecimal("302.00000").stripTrailingZeros();
System.out.println(bd.toString());
Elliott Frisch
  • 191,680
  • 20
  • 149
  • 239