Java get不舍入double的前2个十进制数字

时间:2019-01-30 05:50:31

标签: java

我想获取前2个十进制数字(不舍入)。

这里是一个例子:

49455.10937-> 49455.10

3 个答案:

答案 0 :(得分:1)

格式化为String是一项昂贵的操作(以性能而言) 这可以通过数学运算来完成:

    double x = 49455.10937;
    x *= 100;  // moves two digits from right to left of dec point
    x = Math.floor(x);  // removes all reminaing dec digits
    x /= 100;  // moves two digits from left to right of dec point

答案 1 :(得分:0)

double decimalValue = 49455.10937;
String decimalValueStr = String.valueOf(decimalValue);
int indexDot = decimalValueStr.lastIndexOf('.');
int desiredDigits=3;
String decimal = decimalValueStr.substring(0, (indexDot + 1) + desiredDigits);
decimalValue = Double.parseDouble(decimal);
System.out.println(decimalValue);
//49455.109 is console output (change desired digits)

答案 2 :(得分:-1)

您可以使用格式化程序按如下所示格式化double值

StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
Double value = 49455.10937;
System.out.println(formatter.format("The value: %.2f", value));