以下是Java代码:
double operation = 890 / 1440;
System.out.println(operation);
结果: 0.0
我想要的是保留这个操作的前四位小数 (0.6180)。你知道怎么做吗?
使用一个求值为double而不是int的表达式来初始化你的变量:
double operation = 890.0 / 1440.0;
否则,表达式将使用整数算术进行计算(结果将被截断)。 然后,这个被截断的结果被转换为一个double
。d
- 否则你的数字会被认为是int
类型:
你可以使用双精度字面量 d
- 否则你的数字会被认为是int
类型:
double operation = 890d / 1440d;
那么你可以使用NumberFormat
来指定数字的位数。
例如:
NumberFormat format = new DecimalFormat("#.####");
System.out.println(format.format(operation));
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));
}
}
输出
操作:0.6180555555555556 缩放:0.6181
虽然使用起来很笨拙,但 BigDecimal 提供了一些格式化选项:
BigDecimal first = new BigDecimal(890);
BigDecimal second = new BigDecimal(1440);
System.out.println(first.divide(second, new MathContext(4, RoundingMode.HALF_EVEN)));
double operation = 890.0 / 1440;
System.out.printf(".4f\n", operation);
如果你真的想要将小数点后第一位四舍五入,你也可以使用整数算术,首先通过将第一个数字乘以适当的数量来将其位数向右移动:
long fractionalPart = 10000L * 890L / 1440L;
我在这里使用long类型,以避免临时结果不适合32位而导致溢出。