如何在java中保存十进制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3168580/
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 to save decimal in java
提问by Eric
Having the following code in Java:
在 Java 中有以下代码:
double operation = 890 / 1440;
System.out.println(operation);
Result: 0.0
结果:0.0
What I want is to save the first 4 decimal digits of this operation (0.6180). Do you know how can I do it?
我想要的是保存此操作的前 4 位十进制数字(0.6180)。你知道我该怎么做吗?
回答by Michael Burr
Initialize your variable with an expression that evaluates to a double rather than an int:
使用计算结果为 double 而不是 int 的表达式初始化您的变量:
double operation = 890.0 / 1440.0;
Otherwise the expression is done using integer arithmetic (which ends up truncating the result). That truncated result then gets converted to a double
.
否则,表达式将使用整数算术完成(最终截断结果)。然后该截断的结果被转换为double
.
回答by Bozho
You can use the double literal d
- otherwise your numbers are considered of type int
:
您可以使用 double 文字d
- 否则您的数字被视为类型int
:
double operation = 890d / 1440d;
Then you can use a NumberFormat
to specify the number of digits.
然后您可以使用 aNumberFormat
来指定位数。
For example:
例如:
NumberFormat format = new DecimalFormat("#.####");
System.out.println(format.format(operation));
回答by Greg
This is done using BigDecimal
这是使用 BigDecimal 完成的
import java.math.BigDecimal;
import java.math.RoundingMode;
public class DecimalTest {
/**
* @param args
*/
public static void main(String[] args) {
double operation = 890.0 / 1440.0;
BigDecimal big = new BigDecimal(operation);
big = big.setScale(4, RoundingMode.HALF_UP);
double d2 = big.doubleValue();
System.out.println(String.format("operation : %s", operation));
System.out.println(String.format("scaled : %s", d2));
}
}
Output
输出
operation : 0.6180555555555556 scaled : 0.6181
操作:0.6180555555555556 缩放:0.6181
回答by npinti
回答by Kennet
BigDecimal, although very clumsy to work with, gives some formatting options:
BigDecimal 虽然使用起来很笨拙,但提供了一些格式选项:
BigDecimal first = new BigDecimal(890);
BigDecimal second = new BigDecimal(1440);
System.out.println(first.divide(second, new MathContext(4, RoundingMode.HALF_EVEN)));
回答by J?rn Horstmann
If you really want to round to the first 4 fractional digits you can also use integer arithmetic by first multiplying the first number so its digits are shifted the right amount f places to the left:
如果你真的想四舍五入到前 4 个小数位,你也可以使用整数运算,首先乘以第一个数字,这样它的数字就向左移动了正确的 f 位:
long fractionalPart = 10000L * 890L / 1440L;
I'm using long here to avoid any overflows in case the temporary result does not fit in 32 bits.
我在这里使用 long 来避免任何溢出,以防临时结果不适合 32 位。
回答by ZZ Coder
double operation = 890.0 / 1440;
System.out.printf(".4f\n", operation);