0

Using java(regex) how to strip float decimal having trailing zeros. If the decimal value contains non-zeros[1 to 9] then do not strip.

I tried using java replaceAll as below but its stripping all zeros even if there is non zero value after decimal

new Float(12.50f).toString().replaceAll("\\.0*$", "")

Ex: 12.0 should trim to 12

12.5 should be 12.5

12.50 should be 12.50

12.000 should trim to 12

14.0056 should be 14.0056

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
joe4java
  • 69
  • 11
  • Not sure why this question is marked as duplicate. I did not find answer to my original question. Ex If I have 12.6500 all other answers are trimming to 12.65 but It should not trim that. It must be just 12.6500. My question specifically says trim only if there are exclusive zeros after decimal. – joe4java Apr 01 '19 at 19:22

2 Answers2

3

You should use a NumberFormat to specify how to format your floating point numbers for display. There is no reason to use a regex here.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

You can try this,

s = s.indexOf(".") < 0 ? s : s.replaceAll("0*$", "").replaceAll("\\.$", "");
Jagadesh
  • 2,104
  • 1
  • 16
  • 28