java intvalueexact_Java BigDecimal intvalueExact()用法及代码示例

java.math.BigDecimal.intValueExact()是一个内置函数,它将BigDecimal转换为整数值并检查丢失的信息。如果此BigDecimal的任何小数部分或者转换的结果太大而无法表示为整数值,则此函数将引发算术异常。

用法:

public int intValueExact()

参数:此函数不接受任何参数。

返回值:此函数返回此BigDecimal的整数值。

异常:如果此BigDecimal中有一个非零的小数部分,或者其值太大而无法表示为整数,则该函数将引发ArithmeticException。

例子:

Input : "19878124"

Output : 19878124

Input : "721111"

Output : 721111

以下程序说明了java.math.BigDecimal.intValueExact()方法的用法:

示例1:

// Java program to illustrate

// intValueExact() method

import java.math.*;

import java.io.*;

class GFG {

public static void main(String[] args)

{

// Creating 2 BigDecimal Objects

BigDecimal b1, b2;

// Assigning values to b1, b2

b1 = new BigDecimal("19878124");

b2 = new BigDecimal("721111");

// Displaying their respective Integer Values

System.out.println("Exact Integer Value of " +

b1 + " is " + b1.intValueExact());

System.out.println("Exact Integer Value of " +

b2 + " is " + b2.intValueExact());

}

}

输出:

Exact Integer Value of 19878124 is 19878124

Exact Integer Value of 721111 is 721111

注意:与intValue()函数(该函数丢弃此BigDecimal的任何小数部分并仅在转换结果太大而无法将其表示为整数值时返回低阶32位)不同,此函数在这种情况下会引发算术异常。

示例2:该程序将说明此函数何时引发Exception。

// Java program to illustrate

// Arithmetic Exception occurrence

// in intValueExact() method

import java.math.*;

import java.io.*;

class GFG {

public static void main(String[] args)

{

// Creating 2 BigDecimal Objects

BigDecimal b1, b2;

// Assigning values to b1, b2

b1 = new BigDecimal("3232435121868179");

b2 = new BigDecimal("84561789104423214");

// Displaying their respective Integer Values

// using intValue()

System.out.println("Output by intValue() Function");

System.out.println("The Integer Value of " +

b1 + " is " + b1.intValue());

System.out.println("The Integer Value of " +

b2 + " is " + b2.intValue());

// Exception handling

System.out.println("\nOutput by intValueExact() Function");

try {

System.out.println("Exact Integer Value of " +

b1 + " is " + b1.intValueExact());

System.out.println("Exact Integer Value of " +

b2 + " is " + b2.intValueExact());

}

catch (ArithmeticException e) {

System.out.println("Arithmetic Exception caught");

}

}

}

输出:

Output by intValue() Function

The Integer Value of 3232435121868179 is -214774381

The Integer Value of 84561789104423214 is -920387282

Output by intValueExact() Function

Arithmetic Exception caught

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值