我有一系列Java小数,如:
0.43678436287643872
0.4323424556455654
0.6575643254344554
我想在5位小数后切断所有内容。这怎么可能?
答案 0 :(得分:26)
如果你想保持快速和简单的事情。 ;)
public static void main(String... args) {
double[] values = {0.43678436287643872, 0.4323424556455654, 0.6575643254344554,
-0.43678436287643872, -0.4323424556455654, -0.6575643254344554,
-0.6575699999999999 };
for (double v : values)
System.out.println(v + " => "+roundDown5(v));
}
public static double roundDown5(double d) {
return ((long)(d * 1e5)) / 1e5;
//Long typecast will remove the decimals
}
// Or this. Slightly slower, but faster than creating objects. ;)
public static double roundDown5(double d) {
return Math.floor(d * 1e5) / 1e5;
}
打印
0.43678436287643874 => 0.43678
0.4323424556455654 => 0.43234
0.6575643254344554 => 0.65756
-0.43678436287643874 => -0.43678
-0.4323424556455654 => -0.43234
-0.6575643254344554 => -0.65756
-0.6575699999999999 => -0.65756
答案 1 :(得分:17)
float f = 0.43678436287643872;
BigDecimal fd = new BigDecimal(f);
BigDecimal cutted = fd.setScale(5, RoundingMode.DOWN);
f = cutted.floatValue();
答案 2 :(得分:8)
Double.parseDouble(String.valueOf(x).substring(0,7));
OR
Double.valueOf(String.valueOf(x).substring(0,7));
其中x
包含您要剪切的值,例如0.43678436287643872
答案 3 :(得分:7)
DecimalFormat在这里也可以提供帮助:
double d = 0.436789436287643872;
DecimalFormat df = new DecimalFormat("0.#####");
df.setRoundingMode(RoundingMode.DOWN);
double outputNum = Double.valueOf(df.format(d));
String outpoutString = df.format(d);
答案 4 :(得分:2)
我相信java.text.DecimalFormat
课程就是你所需要的。
答案 5 :(得分:1)
我会用这样的正则表达式来做:
double[] values = {
0.43678436287643872,
0.4323424556455654,
0.6575643254344554,
-0.43678436287643872,
-0.4323424556455654,
-0.6575643254344554
};
Pattern p = Pattern.compile("^(-?[0-9]+[\\.\\,][0-9]{1,5})?[0-9]*$");
for(double number : values) {
Matcher m = p.matcher(String.valueOf(number));
boolean matchFound = m.find();
if (matchFound) {
System.out.println(Double.valueOf(m.group(1)));
}
}
如果您需要支持更多/更少的小数位,可以轻松修改模式。
答案 6 :(得分:1)
概括彼得的回答你可以这样做:
public static double round(double n, int decimals) {
return Math.floor(n * Math.pow(10, decimals)) / Math.pow(10, decimals);
}