[Go] Java decimalformat usage

Source: Internet
Author: User
Tags java decimalformat

We often have to format numbers, such as 2 decimal places, which is the most common. Java provides the DecimalFormat class, which helps you to format numbers as quickly as you like. Here is an example:

  1. Importjava.text.DecimalFormat; publicclasstestnumberformat{Publicstaticvoidmain (String[]args) {doublepi=3.1415927;//pi//Take one-bit integer S   Ystem.out.println (Newdecimalformat ("0"). Format (pi)); 3//Take one-bit integer and two-bit decimal System.out.println (Newdecimalformat ("0.00"). Format (pi));      3.14//Take two-bit integers and three-bit decimals, and the integral parts are filled with 0. System.out.println (New DecimalFormat ("00.000"). Format (pi));//03.142//Take all integral parts System.out.println (newdecimalform   At ("#"). Format (pi)); 3//count in percent and take two decimal System.out.println (new DecimalFormat ("#.##%"). Format (pi));  314.16% longc=299792458; The speed of light//is shown as scientific notation and takes five decimal System.out.println (Newdecimalformat ("#.#### #E0"). Format (c)); 2.99792E8//Displays the scientific notation for two-bit integers and takes four decimal System.out.println (Newdecimalformat ("00.### #E0"). Format (c));      29.9792E7//Every three bits are separated by commas.   System.out.println (Newdecimalformat (", # # #"). Format (c)); 299,792,458//Embed the format in the text System.out.println (Newdecimalformat ("The speed of light is per second, # # #米. "). Format (c));   }  }

    The DecimalFormat class mainly relies on # and 2 placeholder symbols to specify the number length. 0 indicates that if the number of bits is not sufficient, fill with 0, # indicates that the number is pulled up to this position whenever possible. The above example contains almost all the basic usage, if you want to learn more, please refer to the DecimalFormat class documentation.

(Original address: http://blog.csdn.net/wangchangshuai0010/article/details/8577982)

[Go] Java decimalformat usage

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.