如何将数字降至小数点后两位?



我正在尝试将双数据类型数字设置为小数点后两位,但当我输入像150这样的数字时,我只得到一个。

例如,如果我输入:

double num = 150.52152;

Math.floor(num * 100) / 100;

我得到150.52,这是好的!

但是如果我输入double num = 150,我得到的是150.0而不是150.00

如何解决这个问题?

有两种方法

  1. 使用String.format
String.format("%.2f",floorValue)
  1. UsingDecimalFormat
new DecimalFormat("#,##0.00").format(floorValue)

我建议您将new DecimalFormat("#,##0.00")存储到final变量中,并在需要时使用它,而不是每次需要格式化时创建一个新的DecimalFormat对象。

演示:

import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
public static void main(String[] args) {
final NumberFormat format = new DecimalFormat("#,##0.00");// Do it once
double floorValue = 150;
System.out.println(format.format(floorValue));// Use it wherever you need to
// Alternatively
System.out.printf(String.format("%.2f", floorValue));
}
}

输出:

150.00
150.00

控制小数位数是将小数转换为String的函数。记住,你是从以2为底看一个以10为底的值。并非每个这样的值都是可表示的(例如System.out.println(0.05+0.1);)。相反,使用String格式。如,

System.out.printf("%.02f%n", 150.0);

System.out.printf("%.02f%n", 0.05 + 0.1);

要始终在小数点后显示两个值,您可以使用两个输出方法。你的第一份文件如下:

System.out.printf("%.2f", <YOUR VALUE>);

%。2F调用浮点数中的两个小数,该浮点数首先由printf (print float)定义,不能删除,因为整数不能是小数。

第二个选项是使用十进制格式。例如:

// First define your fromat as decimalFormat
DecimalFormat decimalFormat = new DecimalFormat();
// Define number of digits after the decimal point in your case two
decimalFormat.setMaximumFractionDigits(2);
// Print out our result now formated in what we have just defined
System.out.println(decimalFormat.format(<YOUR VALUE>));

虽然你输出的是一个字符串,但它可以是一个浮点数(你可能需要加上"f")在你的值之后确保它被定义)。

希望这是有用的。

您也可以这样做(但我更喜欢String.formatSystem.out.printf)。请注意,后面的零不会显示,因此100.10230将显示为100.1

生成一些数据

Random r =  new Random();
double[] dbls = r.doubles(10).map(d->d*1000).toArray();

打印值

for (double d : dbls) {
double df = (int)(d*100+.5)/100.;
System.out.println(d + " --> " + df);
} 

打印类似的内容

738.2358190119878 --> 738.24
902.7752505591593 --> 902.78
467.26349962571953 --> 467.26
503.2049813704648 --> 503.2
20.288046322504805 --> 20.29
409.10379837674714 --> 409.1
559.2821881121522 --> 559.28
288.5513513499909 --> 288.55
124.07583289719682 --> 124.08
535.1799354550361 --> 535.18