将Double转换为BigDecimal并设置BigDecimal精度 [英] Convert double to BigDecimal and set BigDecimal Precision
问题描述
在Java中,我想取一个double值并将其转换成一个 BigDecimal
,并将其String值打印到一定的精度。
In Java, I want to take a double value and convert it to a BigDecimal
and print out its String value to a certain precision.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
double d=-.00012;
System.out.println(d+""); //This prints -1.2E-4
double c=47.48000;
BigDecimal b = new BigDecimal(c);
System.out.println(b.toString());
//This prints 47.47999999999999687361196265555918216705322265625
}
}
它打印这个巨大的事情:
It prints this huge thing:
47.479999999999687361196265555918216705322265625
47.47999999999999687361196265555918216705322265625
而不是
47.48
47.48
我正在做 BigDecimal
转换有时双重值将包含很多小数位(即 - 。000012
)和将double转换为String时会产生科学符号 -1.2E-4
。我想以非科学记谱法存储String值。
The reason I'm doing the BigDecimal
conversion is sometimes the double value will contain a lot of decimal places (i.e. -.000012
) and the when converting the double to a String will produce scientific notation -1.2E-4
. I want to store the String value in non-scientific notation.
我想让BigDecimal总是有两个这样的精度单位:47.48。 BigDecimal可以限制转换为字符串的精度吗?
I want to have BigDecimal always have two units of precision like this: "47.48". Can BigDecimal restrict precision on conversion to string?
推荐答案
如果您使用另一个MathContext :
BigDecimal b = new BigDecimal(d, MathContext.DECIMAL64);
只需选择所需的上下文。
Just pick the context you need.
这篇关于将Double转换为BigDecimal并设置BigDecimal精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!