如何在 Java 中格式化数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I format a number in Java?
提问by ScArcher2
How do I format a number in Java?
What are the "Best Practices"?
如何在 Java 中格式化数字?
什么是“最佳实践”?
Will I need to round a number before I format it?
在格式化之前是否需要舍入数字?
32.302342342342343
=>32.30
.7323
=>0.73
32.302342342342343
=>32.30
.7323
=>0.73
etc.
等等。
采纳答案by Espo
From this thread, there are different ways to do this:
从这个线程,有不同的方法来做到这一点:
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
The DecimalFormat()seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.
该DecimalFormat的()似乎是最有活力的方式去做,而且也很容易阅读别人的代码时,理解。
回答by Jeff Atwood
You and String.format()
will be new best friends!
你,String.format()
将是新的最好的朋友!
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
https://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
String.format("%.2f", (double)value);
回答by ckpwong
Use DecimalFormat.
使用十进制格式。
回答by Vinko Vrsalovic
Round numbers, yes. This is the 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]);
}
}
}
回答by Tom Hawtin - tackline
There are two approaches in the standard library. One is to use java.text.DecimalFormat. The other more cryptic methods (String.format, PrintStream.printf, etc) based around java.util.Formatter should keep C programmers happy(ish).
标准库中有两种方法。一种是使用java.text.DecimalFormat。基于 java.util.Formatter 的其他更神秘的方法(String.format、PrintStream.printf 等)应该让 C 程序员高兴(ish)。
回答by Robert J. Walker
Be aware that classes that descend from NumberFormat (and most other Format descendants) are not synchronized. It is a common (but dangerous) practice to create format objects and store them in static variables in a util class. In practice, it will pretty much always work until it starts experiencing significant load.
请注意,从 NumberFormat(和大多数其他 Format 后代)继承的类是不同步的。创建格式对象并将它们存储在 util 类中的静态变量中是一种常见(但危险)的做法。在实践中,它几乎总是可以工作,直到它开始承受大量负载。
回答by Stefan Haberl
As Robert has pointed out in his answer: DecimalFormat is neither synchronized nor does the API guarantee thread safety (it might depend on the JVM version/vendor you are using).
正如罗伯特在他的回答中指出的那样:DecimalFormat 既不同步也不保证线程安全(它可能取决于您使用的 JVM 版本/供应商)。
Use Spring's Numberformatterinstead, which is thread safe.
改用 Spring 的Numberformatter,它是线程安全的。
回答by Nautilus
Try this:
尝试这个:
String.format("%.2f", 32.302342342342343);
Simple and efficient.
简单高效。
回答by snr
public static void formatDouble(double myDouble){
NumberFormat numberFormatter = new DecimalFormat("##.000");
String result = numberFormatter.format(myDouble);
System.out.println(result);
}
For instance, if the double value passed into the formatDouble() method is 345.9372, the following will be the result: 345.937 Similarly, if the value .7697 is passed to the method, the following will be the result: .770
例如,如果传递给 formatDouble() 方法的 double 值为 345.9372,则结果如下: 345.937 同样,如果将值 .7697 传递给方法,则结果如下: .770