Removing the .0 from a double

无人久伴 提交于 2019-12-22 07:19:18

问题


I am trying to display numbers in a string dynamically, so if the number has decimal's display them but if not don"t show the .0

example: display 5.5 as 5.5 and 5.0 as 5

This is what I have so far: (answer is a double)

double temp = answer;
long temp2 = (long) temp;
if (temp == temp2) {
output = String.valueOf(temp2);
System.out.println(output);

this work's fine up to about 1e18 then will error out because of the maximum size of a Long. So how would I achieve this on bigger numbers like 5.43e86


回答1:


Use DecimalFormat

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



回答2:


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.




回答3:


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



回答4:


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

you would want just DecimalFormat("0.0")



来源:https://stackoverflow.com/questions/7109388/removing-the-0-from-a-double

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