nik*_*hil 1 java math truncate
我正在解决一个需要截断输出的问题,令我惊讶的是,我无法找到一种在 java 中截断数字的方法。
输出需要是后跟 6 位小数的数字。
我想要的是
double truncate(double number,int places)输出是
truncate(14/3.0) = 4.666666.
但我得到的是
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
// rounds( 14/3.0 , 6 ) = 4.666667
Run Code Online (Sandbox Code Playgroud)
随着String.format我得到
String.format("%.6f", 14/3.0) = 4.666667
Run Code Online (Sandbox Code Playgroud)
我还尝试了我在 stackoverflow 上找到的一个解决方案,该解决方案建议使用 BigDecimal 并且给了我相同的答案。
NumberFormat 似乎也以同样的方式工作
java.text.NumberFormat f = java.text.NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(6);
System.out.println(f.format(14/3.0)); // 4.666667
Run Code Online (Sandbox Code Playgroud)
是否有内置方法可以执行此操作,还是我需要使用 BigInteger 之类的方法编写自己的方法?有什么我做错了吗?
这是因为你不是截断而是四舍五入:
long tmp = Math.round(value);
Run Code Online (Sandbox Code Playgroud)
如果您改用演员表,它应该可以工作:
long tmp = (long) value;
Run Code Online (Sandbox Code Playgroud)
所以下面的代码输出4.666666如你所愿:
public static void main(String[] args) throws Exception {
System.out.println(truncate(14/3.0, 6));
}
public static double truncate(double value, int places) {
if (places < 0) {
throw new IllegalArgumentException();
}
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = (long) value;
return (double) tmp / factor;
}
Run Code Online (Sandbox Code Playgroud)