Scientific notation to decimal

亡梦爱人 提交于 2019-12-12 01:50:00

问题


I have a double and i am trying to convert it to a decimal. When i use decimalformat to achieve this i get the following:

public void roundNumber(){
    double d = 2.081641999208976E-4;
    JOptionPane.showMessageDialog(null,roundFiveDecimals(d));
}

public double roundFiveDecimals(double d) {
    DecimalFormat df = new DecimalFormat("#.#####");
    return Double.valueOf(df.format(d));
}

I want the output to be .00021; however, i get 2.1E-4. Can anyone help explain how to get .00021 and not 2.1E-4?


回答1:


You're parsing the result from DecimalFormat - you should be returning it as a String:

public String roundFiveDecimals(double d) {
    DecimalFormat df = new DecimalFormat("#.#####");
    return df.format(d);
}

The double value itself has no concept of formatting - it's just a number. It's the job of DecimalFormat to format the value into text however you want... if you then convert that text back into a number, you've lost that work.



来源:https://stackoverflow.com/questions/6878623/scientific-notation-to-decimal

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