In Java, how to remove all 0s in a float?

I want to change the float as follows:

10.5000 โ†’ 10.5 10.0000 โ†’ 10

How can I remove all zeros after a decimal point and change it as a float (if there were no zeros) or int (if there were only zeros)?

Thanks in advance.

+4
source share
7 answers

Why not try regexp?

new Float(10.25000f).toString().replaceAll("\\.?0*$", "") 
+10
source

Well, the trick is that the floats and double themselves do not actually have trailing zeros; it's just how they are printed (or initialized as literals) that can show them. Consider the following examples:

 Float.toString(10.5000); // => "10.5" Float.toString(10.0000); // => "10.0" 

You can use DecimalFormat to fix the example "10.0":

 new java.text.DecimalFormat("#").format(10.0); // => "10" 
+16
source

Format the numbers for your output as needed. You cannot delete internal values โ€‹โ€‹of "0".

+1
source

This handles two different formatting:

 double d = 10.5F; DecimalFormat formatter = new DecimalFormat("0"); DecimalFormat decimalFormatter = new DecimalFormat("0.0"); String s; if (d % 1L > 0L) s = decimalFormatter.format(d); else s = formatter.format(d); System.out.println("s: " + s); 
+1
source

java.math.BigDecimal has a stripTrailingZeros () method that will achieve what you are looking for.

 BigDecimal myDecimal = new BigDecimal(myValue); myDecimal.stripTrailingZeros(); myValue = myDecimal.floatValue(); 
+1
source

Try using System.out.format

Here is a link that allows you to format the style c http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

0
source

I had the same problem and find a workaround in the following link: fooobar.com/questions/18363 / ...

The answer from JasonD was the one I followed. It is language independent which was good for my problem and had no problems with long meanings.

I hope for this help.

ADD CONTENT FROM LINE ABOVE:

 public static String fmt(double d) { if(d == (long) d) return String.format("%d",(long)d); else return String.format("%s",d); } 

It produces:

 232 0.18 1237875192 4.58 0 1.2345 
0
source

Source: https://habr.com/ru/post/1384196/


All Articles