Java retains two decimal places (rounded)

Source: Internet
Author: User

Import Java.math.bigdecimal;import Java.text.decimalformat;import Java.text.numberformat;public class TestNumber { public static Double num = 3.1015926;public static Double zero = 0.00000;//method One: printing is easiest, always at the end there is a two-bit decimal public static void function 1 () {System.out.println (String.Format ("%.2f", num)); System.out.println (String.Format ("%.2f", Zero));} Method Two: After conversion is a string type public static void Function2 () {DecimalFormat df = new DecimalFormat ("0.00"); SYSTEM.OUT.PRINTLN (Df.format (num)); System.out.println (Df.format (zero));} Method Three: After conversion is a double type, but will omit the last 0, only one bit of 0public static void Function3 () {BigDecimal bg1 = new BigDecimal (num);d ouble finalnum = Bg1.setscale (2, bigdecimal.round_half_up). Doublevalue (); System.out.println (Finalnum); BigDecimal bg2 = new BigDecimal (zero);d ouble Finalzero = Bg2.setscale (2, bigdecimal.round_half_up). Doublevalue (); System.out.println (Finalzero);} Method Four: The end of 0 will omit 3.1001->3.1,0.0000->0public static void Function4 () {NumberFormat NF = Numberformat.getnumberinstance (); Nf.setmaximumfractiondIgits (2); SYSTEM.OUT.PRINTLN (Nf.format (num)); System.out.println (Nf.format (zero));} public static void Main (String args[]) {System.out.println ("function1:"); function1 (); System.out.println ("function2:"); function2 (); System.out.println ("Function3:"); Function3 (); System.out.println ("Function4:"); Function4 ();}}

Results show:


Java retains two decimal places (rounded)

Related Article

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.