Java 不使用科学符号将字符串转换为双精度
我在互联网上搜索过,但找不到任何解决方案(也许,我搜索得不好)。Java 不使用科学符号将字符串转换为双精度,java,string,double,Java,String,Double,我在互联网上搜索过,但找不到任何解决方案(也许,我搜索得不好)。 我想将字符串“108595000.5”转换为双精度,我使用了以下方法: Double.parseDouble("108595000.5"); Double.valueOf("108595000.5"); 不幸的是,它们都返回1.08595E8 如何将此字符串转换为双精度而不会出现问题?尝试使用 value = new BigDecimal(yourString); doubleValue = value.doubleValue(
我想将
字符串
“108595000.5”
转换为双精度
,我使用了以下方法:
Double.parseDouble("108595000.5");
Double.valueOf("108595000.5");
不幸的是,它们都返回1.08595E8
如何将此
字符串
转换为双精度
而不会出现问题?尝试使用
value = new BigDecimal(yourString);
doubleValue = value.doubleValue();
如果需要精确的值
如果您想在后面加两个数字,“
您使用的方法不会返回
1.08595E8
,而是返回数字,您抱怨的是控制台中该数字的表示形式(或作为字符串
)
但是,您可以指定如何使用指定的格式自己输出双精度,请参见以下示例:
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
工程:108595000.5
普通:108595000.5
四舍五入固定小数位数:108595000.50
1.08595E8'
是108595000.5数字的正确表示,刚刚用科学记数法写成。输出中有什么问题?double将返回该值,仅当您关心输出时,使用BigDecimal
。。。它将保存正确的double
,但可以很容易地用不同的符号打印出来。很难将您的头缠绕在它周围,但是double
根本不“保存科学符号”或任何符号。它代表一个数字。该数字的打印方式取决于您的打印方式。您将表示(打印值)与double
变量的实际值混淆了。@mn到底是什么问题?
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));
}