在 Java 中设置大十进制值的小数位
我们有以下 BigDecimal 值 −
BigDecimal val1 = new BigDecimal("37578975587.876876989");
我们已经将小数位设为 −
int decPlaces1 = 3;
现在,我们将使用 ROUND_DOWN 字段将舍入模式设置为朝零舍入 −
// ROUND_DOWN val1 = val1.setScale(decPlaces1, BigDecimal.ROUND_DOWN); String str1 = val1.toString(); System.out.println("Result = "+str1);
若要在 Java 中设置 BigDecimal 值的小数位,请尝试以下代码 −
示例
import java.math.BigDecimal; public class Demo { public static void main(String[] argv) throws Exception { int decPlaces1 = 3; int decPlaces2 = 5; BigDecimal val1 = new BigDecimal("37578975587.876876989"); BigDecimal val2 = new BigDecimal("62567875598.976876569"); System.out.println("Value 1 : "+val1); System.out.println("Value 2 : "+val2); // ROUND_DOWN val1 = val1.setScale(decPlaces1, BigDecimal.ROUND_DOWN); String str1 = val1.toString(); System.out.println("Result = "+str1); // ROUND_UP val2 = val2.setScale(decPlaces2, BigDecimal.ROUND_UP); String str2 = val2.toString(); System.out.println("Result = "+str2); } }
输出
Value 1 : 37578975587.876876989 Value 2 : 62567875598.976876569 Result = 37578975587.876 Result = 62567875598.97688
推广