in Java, how to delete all 0s in float?

爱⌒轻易说出口 提交于 2019-12-19 08:11:22

问题


I'd like to change float like this way:

10.5000 -> 10.5 10.0000 -> 10

How can I delete all zeros after the decimal point, and change it either float (if there's non-zeros) or int (if there were only zeros)?

Thanks in advance.


回答1:


Why not try regexp?

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



回答2:


Well the trick is that floats and doubles themselves don't really have trailing zeros per se; it's just the way they are printed (or initialized as literals) that might show them. Consider these examples:

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

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

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



回答3:


java.math.BigDecimal has a stripTrailingZeros() method, which will achieve what you're looking for.

BigDecimal myDecimal = new BigDecimal(myValue);
myDecimal.stripTrailingZeros();
myValue = myDecimal.floatValue();



回答4:


This handles it with two different formatters:

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);



回答5:


Format your numbers for your output as required. You cannot delete the internal "0" values.




回答6:


You just need to use format class like following:

new java.text.DecimalFormat("#.#").format(10.50000);
new java.text.DecimalFormat("#.#").format(10.00000);



回答7:


Try using System.out.format

Heres a link which allows c style formatting http://docs.oracle.com/javase/tutorial/java/data/numberformat.html




回答8:


I had the same issue and find a workaround in the following link: StackOverFlow - How to nicely format floating numbers to string without unnecessary decimal 0

The answer from JasonD was the one I followed. It's not locale-dependent which was good for my issue and didn't have any problem with long values.

Hope this help.

ADDING CONTENT FROM LINK ABOVE:

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

Produces:

232
0.18
1237875192
4.58
0
1.2345


来源:https://stackoverflow.com/questions/8347478/in-java-how-to-delete-all-0s-in-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!