不使用科学记数法将字符串转换为双精度
Convert string to double without scientific notation
我已经在网上搜索了,但没有找到任何解决方案(也许是我搜索不好)。
我想将 String
"108595000.5"
转换为 double
并且我使用了这些方法:
Double.parseDouble("108595000.5");
Double.valueOf("108595000.5");
不幸的是,他们两个return 1.08595E8
。
我怎样才能毫无问题地将这个 String
转换为 double
?
尝试使用
value = new BigDecimal(yourString);
doubleValue = value.doubleValue();
如果您想要精确的值。
如果你想要 ","
之后的 2 个数字
double a = yourDouble;
System.out.printf("%.2f",a)
你用的方法不是return1.08595E8
,而是return这个数字,你抱怨的是该数字在控制台中的表示(或作为 String
)。
但是,您可以自己指定如何使用指定的格式输出 double
,请参见以下示例:
public static void main(String[] args) {
String value = "108595000.5";
// use a BigDecimal to parse the value
BigDecimal bd = new BigDecimal(value);
// choose your desired output:
// either the String representation of a double (undesired)
System.out.println("double:\t\t\t\t\t" + bd.doubleValue());
// or an engineering String
System.out.println("engineering:\t\t\t\t" + bd.toEngineeringString());
// or a plain String (might look equal to the engineering String)
System.out.println("plain:\t\t\t\t\t" + bd.toPlainString());
// or you specify an amount of decimals plus a rounding mode yourself
System.out.println("rounded with fix decimal places:\t"
+ bd.setScale(2, BigDecimal.ROUND_HALF_UP));
}
double: 1.085950005E8
engineering: 108595000.5
plain: 108595000.5
rounded with fix decimal places: 108595000.50
我已经在网上搜索了,但没有找到任何解决方案(也许是我搜索不好)。
我想将 String
"108595000.5"
转换为 double
并且我使用了这些方法:
Double.parseDouble("108595000.5");
Double.valueOf("108595000.5");
不幸的是,他们两个return 1.08595E8
。
我怎样才能毫无问题地将这个 String
转换为 double
?
尝试使用
value = new BigDecimal(yourString);
doubleValue = value.doubleValue();
如果您想要精确的值。
如果你想要 ","
double a = yourDouble;
System.out.printf("%.2f",a)
你用的方法不是return1.08595E8
,而是return这个数字,你抱怨的是该数字在控制台中的表示(或作为 String
)。
但是,您可以自己指定如何使用指定的格式输出 double
,请参见以下示例:
public static void main(String[] args) {
String value = "108595000.5";
// use a BigDecimal to parse the value
BigDecimal bd = new BigDecimal(value);
// choose your desired output:
// either the String representation of a double (undesired)
System.out.println("double:\t\t\t\t\t" + bd.doubleValue());
// or an engineering String
System.out.println("engineering:\t\t\t\t" + bd.toEngineeringString());
// or a plain String (might look equal to the engineering String)
System.out.println("plain:\t\t\t\t\t" + bd.toPlainString());
// or you specify an amount of decimals plus a rounding mode yourself
System.out.println("rounded with fix decimal places:\t"
+ bd.setScale(2, BigDecimal.ROUND_HALF_UP));
}
double: 1.085950005E8
engineering: 108595000.5
plain: 108595000.5
rounded with fix decimal places: 108595000.50