简体   繁体   中英

Java: Converting a double to a String

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM