Java: Converting a double to a String

回眸只為那壹抹淺笑 提交于 2020-01-28 09:59:05

问题


I have a double whose value is 10,000,000.00 (ten millions). I have to convert it to a String. When using the method toString I am getting the String "1.0E7" which is correct following the specification. Unfortunately I need the String "10,000,000.00" (or the equivalent depending on the locale).

How can achieve this?


回答1:


Try either

NumberFormat http://java.sun.com/javase/6/docs/api/java/text/NumberFormat.html

DecimalFormat http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html




回答2:


In addition to the formatter, you might consider using the java.math.BigDecimal class to represent numbers precisely.

Calculations where complete accuracy is required, such as financial calculations, are best performed with BigDecimal. Floating point math is better for engineering, graphics, and other mathematical computations where some accuracy can be sacrificed for speed.




回答3:


  public static void main(String[] args) throws ParseException {
    double aDouble = 10000000.00;
    DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(Locale.US);
    String aString = Double.toString(aDouble);
    System.out.println(nf.parse(aString));
  }



回答4:


Look into "DecimalFormat". It lets you format the output pretty much however you want!



来源:https://stackoverflow.com/questions/1521122/java-converting-a-double-to-a-string

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