[英]Java: Converting a double to a String
I have a double whose value is 10,000,000.00 (ten millions).我有一个双精度值是 10,000,000.00(千万)。 I have to convert it to a String
.我必须将其转换为String
。 When using the method toString
I am getting the String
"1.0E7" which is correct following the specification.当使用toString
方法时,我得到了符合规范的String
“1.0E7”。 Unfortunately I need the String
"10,000,000.00" (or the equivalent depending on the locale).不幸的是,我需要String
“10,000,000.00”(或等价物,具体取决于语言环境)。
How can achieve this?怎样才能做到这一点?
Try either尝试
NumberFormat http://java.sun.com/javase/6/docs/api/java/text/NumberFormat.html 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十进制格式http://java.sun.com/javase/6/docs/api/java/text/DecimalFormat.html
In addition to the formatter, you might consider using the java.math.BigDecimal
class to represent numbers precisely.除了格式化程序之外,您还可以考虑使用java.math.BigDecimal
类来精确表示数字。
Calculations where complete accuracy is required, such as financial calculations, are best performed with BigDecimal
.需要完全准确的计算(例如财务计算)最好使用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!它可以让您随意格式化输出!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.