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

时光毁灭记忆、已成空白 提交于 2019-12-01 06:19:15

Why not try regexp?

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

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"

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

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

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

You just need to use format class like following:

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

Try using System.out.format

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

Jacqueline Rodriguez

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