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,798
  • 5
  • 37
  • 45
Marjer
  • 1,313
  • 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
  • 46,415
  • 5
  • 60
  • 76
  • @Marjer: If you don't want to convert to and back from double then you could try `System.out.println(val.replaceAll("(\\..+?)(0*)$", "$1"));`. – Bhesh Gurung Jun 13 '14 at 19:05
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
  • 621
  • 3
  • 20
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,774
  • 1
  • 13
  • 15
0

You could construct a BigDecimal and use stripTrailingZeros().

BigDecimal bd = new BigDecimal("302.00000").stripTrailingZeros();
System.out.println(bd.toString());
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249