Removing the .0 from a double

落爺英雄遲暮 提交于 2019-12-05 08:31:53
Kal

Use DecimalFormat

double answer = 5.0;
DecimalFormat df = new DecimalFormat("###.#");
System.out.println(df.format(answer));

The DecimalFormat suggestions are the easiest way to handle this. If they aren't sufficient, here's another idea.

If you're starting to hit the maximum values that can be represented by primitives in Java, then you may need to move to BigInteger and BigDecimal.

Try playing around with the BigDecimal.toBigInteger() method coupled with the toString() methods on BigDecimal and BigInteger.

It's not good solution if you use new DecimalFormat("0.#") you are missing data, for example PI = 3.14, but after parse you ae geting 3.1

Another solution to use eval%1 ? (int)d : d this time couse max integer limit , again missing data

my solution is working, but it's not good idea

res = removeLastChars(eval,".0");

private String removeLastChars(double eval, String text){

    String res = String.valueOf(eval);
    int length = text.length();

    if (res.length() > length){
        res = res.substring((res.length() - length), res.length()).equals(text)
                ? res.substring(0, (res.length() - length)) : res;
    }

    return res;
}

Look at http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

you would want just DecimalFormat("0.0")

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