溫馨提示×

java中bigdecimal轉(zhuǎn)成int怎么實現(xiàn)

小億
195
2023-12-21 09:49:22
欄目: 編程語言

在Java中,可以使用intValue()方法將BigDecimal對象轉(zhuǎn)換為int類型。示例如下:

BigDecimal decimal = new BigDecimal("123.45");
int intValue = decimal.intValue();
System.out.println(intValue); // 輸出 123

注意,intValue()方法會將BigDecimal對象進(jìn)行截斷,并返回整數(shù)部分的值。如果希望進(jìn)行四舍五入,可以使用setScale()方法指定精度,然后再使用intValue()方法進(jìn)行轉(zhuǎn)換,如下所示:

BigDecimal decimal = new BigDecimal("123.45");
BigDecimal roundedDecimal = decimal.setScale(0, RoundingMode.HALF_UP); // 四舍五入保留整數(shù)部分
int intValue = roundedDecimal.intValue();
System.out.println(intValue); // 輸出 123

0