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
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
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
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("\\.$", "");
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
You could construct a BigDecimal and use stripTrailingZeros().
BigDecimal bd = new BigDecimal("302.00000").stripTrailingZeros();
System.out.println(bd.toString());