Format a number

Source: Internet
Author: User
We often need to format numbers, such as taking 2 decimal places, which is the most common. Java provides the decimalformat class to help you format numbers as quickly as possible. The following is an example: Import Java. text. decimalformat; public class testnumberformat {public static void main (string [] ARGs) {double Pi = 3.1415927; // The circumference rate // gets an integer system. out. println (New decimalformat ("0 "). format (PI); // 3 // take an integer and two decimal places system. out. println (New decimalformat ("0.00 "). format (PI); // 3.14 // take two integers and three decimal places. The less integer is filled with 0. System. out. println (New decimalformat ("00.000 "). format (PI); // 03.142 // obtain all integer parts of the system. out. println (New decimalformat ("#"). format (PI); // 3 // count by percentage, and take two decimal places system. out. println (New decimalformat ("#. # % "). format (PI); // 314.16% long c = 299792458; // speed of light // display as a scientific notation, and take the five decimal places system. out. println (New decimalformat ("#. ##### E0 "). format (c); // 2.99792e8 // displays the scientific notation of two integers, and takes four decimal places. out. println (New decimalformat ("00. #### E0 "). format (c); // 29.9792e7 // each three digits are separated by commas. out. println (New decimalformat (",###"). format (c); // 299,792,458 // embed the format into the text system. out. println (New decimalformat ("the speed of light is every second, ### meters. "). Format (c) ;}} running result: 33.1403.1423314.16% 2.99792e829.9792e7299, 792,458 light speed is 299,792,458 meters per second. The decimalformat class mainly uses the # And 0 placeholder numbers to specify the number length. 0 indicates that if the number of digits is insufficient, it is filled with 0. # indicates that the number is pulled to this position whenever possible. The above example contains almost all basic usage

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.