Java Decimal class and rounding method with very high precision decimal time

Source: Internet
Author: User


Note If the result is an infinite number of decimal places, you will get an error if you do not specify a digit rounding


Import Java.util.scanner;import Java.math.bigdecimal;public class Main {public static void main (String args[]) {Scanner in = new Scanner (system.in); BigDecimal a = In.nextbigdecimal (); BigDecimal B = in.nextbigdecimal (); System.out.println ("Add" + a.add (b)); System.out.println ("Sub" + a.subtract (b)); System.out.println ("Mul" + a.multiply (b)); System.out.println ("Divide" + a.divide (b));//here If the result is an infinite loop, you will get an error System.out.println ("Rounding:" + a.divide (b,5, BIGDECIMAL.ROUND_HALF_UP));//The second parameter is the number of decimal digits  a.divide (b,5,bigdecimal.round_half_up). doublevalue;double D1 = 3.1415926; BigDecimal T1 = new BigDecimal (D1); You can convert the Doubletobigdecimal int d2 = 3214856 in turn; BigDecimal t2 = new BigDecimal (D2); BigDecimal t3 = new BigDecimal ("843269136"); System.out.println ("Dobule to:" + T1); System.out.println ("Int to:" + T2); System.out.println ("String to:" + T3);}}


Java Decimal class and rounding method with very high precision decimal time

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.