2008-09-08 78 views

Trả lời

106

Từ this thread, có nhiều cách khác nhau để làm điều này:

double r = 5.1234; 
System.out.println(r); // r is 5.1234 

int decimalPlaces = 2; 
BigDecimal bd = new BigDecimal(r); 

// setScale is immutable 
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); 
r = bd.doubleValue(); 

System.out.println(r); // r is 5.12 

f = (float) (Math.round(n*100.0f)/100.0f); 

DecimalFormat df2 = new DecimalFormat("#,###,###,##0.00"); 
double dd = 100.2397; 
double dd2dec = new Double(df2.format(dd)).doubleValue(); 

// The value of dd2dec will be 100.24 

Các DecimalFormat() có vẻ là cách năng động nhất để làm điều đó, và nó cũng rất dễ hiểu khi đọc người khác mã.

+0

Cảm ơn lời giải thích này. Tuy nhiên, Intellij khuyến nghị sử dụng 'Double.valueOf' thay vì' new Double (number) .doubleValue() '. Dòng cuối cùng của ví dụ cuối cùng sẽ là 'double dd2dec = Double.valueOf (df2.format (dd)); ' – kumaheiyama

66

Bạn và String.format() sẽ là bạn bè mới tốt nhất!

http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#syntax

String.format("%.2f", (double)value); 
+23

Câu trả lời này sẽ không có quá nhiều upvotes nếu nó đến từ bất cứ ai khác. 'String.format' là dành cho các chuỗi định dạng, không phải là số. –

+3

Thực ra, String.format giống như printf của C. Nó có thể định dạng một số loại dữ liệu. – cesarse

+2

Khi bạn muốn chuyển đổi giá trị làm tròn thành chuỗi, đây là một trong những cách. Khác đang sử dụng 'DecimalFormat'. Và 'DecimalFormat' hơi nhanh hơn' String.format'. 'System.currentTimeMillis' diff đơn giản cho thấy điều đó. – manikanta

11

Số vòng, vâng. Đây là main example source.

/* 
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. 
* 
* Redistribution and use in source and binary forms, with or without 
* modification, are permitted provided that the following conditions 
* are met: 
* 
* - Redistributions of source code must retain the above copyright 
*  notice, this list of conditions and the following disclaimer. 
* 
* - Redistributions in binary form must reproduce the above copyright 
*  notice, this list of conditions and the following disclaimer in the 
*  documentation and/or other materials provided with the distribution. 
* 
* - Neither the name of Sun Microsystems nor the names of its 
*  contributors may be used to endorse or promote products derived 
*  from this software without specific prior written permission. 
* 
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS 
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
*/ 


import java.util.*; 
import java.text.*; 

public class DecimalFormatDemo { 

    static public void customFormat(String pattern, double value) { 
     DecimalFormat myFormatter = new DecimalFormat(pattern); 
     String output = myFormatter.format(value); 
     System.out.println(value + " " + pattern + " " + output); 
    } 

    static public void localizedFormat(String pattern, double value,          Locale loc) { 
     NumberFormat nf = NumberFormat.getNumberInstance(loc); 
     DecimalFormat df = (DecimalFormat)nf; 
     df.applyPattern(pattern); 
     String output = df.format(value); 
     System.out.println(pattern + " " + output + " " + loc.toString()); 
    } 

    static public void main(String[] args) { 

     customFormat("###,###.###", 123456.789); 
     customFormat("###.##", 123456.789); 
     customFormat("000000.000", 123.78); 
     customFormat("$###,###.###", 12345.67); 
     customFormat("\u00a5###,###.###", 12345.67); 

     Locale currentLocale = new Locale("en", "US"); 

     DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale); 
     unusualSymbols.setDecimalSeparator('|'); 
     unusualSymbols.setGroupingSeparator('^'); 
     String strange = "#,##0.###"; 
     DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols); 
     weirdFormatter.setGroupingSize(4); 
     String bizarre = weirdFormatter.format(12345.678); 
     System.out.println(bizarre); 

     Locale[] locales = { 
      new Locale("en", "US"), 
      new Locale("de", "DE"), 
      new Locale("fr", "FR") 
     }; 

     for (int i = 0; i < locales.length; i++) { 
      localizedFormat("###,###.###", 123456.789, locales[i]); 
     } 
    } 
} 
4

Có hai phương pháp tiếp cận trong thư viện chuẩn. Một là sử dụng java.text.DecimalFormat. Các phương thức khó hiểu khác (String.format, PrintStream.printf, vv) dựa trên java.util.Formatter nên giữ cho các lập trình viên C vui vẻ (ish).

12

Hãy lưu ý rằng các lớp học đến từ NumberFormat (và hầu hết các con cháu Định dạng khác) không được đồng bộ hóa. Đó là một thực tế phổ biến (nhưng nguy hiểm) để tạo các đối tượng định dạng và lưu trữ chúng trong các biến tĩnh trong một lớp util. Trong thực tế, nó sẽ khá nhiều luôn luôn làm việc cho đến khi nó bắt đầu trải qua tải trọng đáng kể.

2

Như Robert đã chỉ ra trong câu trả lời của mình: DecimalFormat không được đồng bộ hóa cũng như API đảm bảo an toàn luồng (nó có thể phụ thuộc vào phiên bản JVM/nhà cung cấp bạn đang sử dụng).

Sử dụng Spring Numberformatter để thay thế, đó là chuỗi an toàn.

8

Hãy thử điều này:

String.format("%.2f", 32.302342342342343); 

đơn giản và hiệu quả.

0
public static void formatDouble(double myDouble){ 
NumberFormat numberFormatter = new DecimalFormat("##.000"); 
String result = numberFormatter.format(myDouble); 
System.out.println(result); 
} 

Ví dụ, nếu giá trị tăng gấp đôi thông qua vào formatDouble() phương pháp là 345,9372, sau đây sẽ thể là kết quả: 345,937 Tương tự như vậy, nếu giá trị 0,7697 được truyền cho phương pháp này, sau đây sẽ là kết quả: .770

Các vấn đề liên quan