Groovy Tip BigDecimal Data type

Source: Internet
Author: User

One place where the groovy language is easier to use than the Java language is that the groovy language introduces the operation of the size number. Of course, the number of sizes we're talking about here is that the precision exceeds the float and double decimal. We may have to deal with the size of the number of cases, if it is in the Java language, we can only be or use Java.math.BigDecimal to deal with, of course, it is very inconvenient to use, or simply design their own data types to solve the problem of size. However, in the groovy language, we can use the BigDecimal data type directly to solve this problem.

In the groovy language, the default type of decimal is the BigDecimal type.

println 1.2.class.name

The results of the operation are:

Java.math.BigDecimal

Here, when you do the INT type division, there's a difference between the groovy language and the Java language that needs to be raised.

In the Java language, the following operation:

System.out.println (1/2);

The result is 0.

If you want to get decimals, you must do the following:

System.out.println ((float) 1/2);

In the groovy language, the following operation:

println (1/2)

The result is 0.5.

If you want to complete the operation, you must do the following:

println ((1/2) as int)

In the groovy language, we can also use a negative exponent to represent the type of size. Such as:

println 1.2e-39

So, we initialize the way a number of sizes can use decimals and negative exponents. Such as:

def BD1 = 1.23044953333333333

def BD2 = 1.3e-45

println Bd1.class.name

println Bd2.class.name

The results of the operation are:

Java.math.BigDecimal

Java.math.BigDecimal

Of course, we can also initialize a large decimal number with a numeric string. Such as:

def bd3 = ' 1.3e-40 ' as BigDecimal

def BD4 = new BigDecimal (' 1.3e-40 ')

println Bd3.class.name

println Bd4.class.name

The results of the operation are:

Java.math.BigDecimal

Java.math.BigDecimal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.