Java easy way to keep n decimal places __java

Source: Internet
Author: User


There are a lot of times when we need to format some numbers to show that there are four more common ways to summarize:


Package com.example.test.df;
Import Java.math.BigDecimal;
Import Java.text.DecimalFormat;

Import Java.text.NumberFormat;

	public class Decimalformattest {private static float number = -128.735f;
		public static void Main (string[] args) {numberformat_1 ();
		Numberformat_2 ();
		Numberformat_3 ();
	Numberformat_4 ();
/** * DecimalFormat Conversion is easiest/public static void Numberformat_1 () {DecimalFormat df = new DecimalFormat (". 00");
		DecimalFormat df = new DecimalFormat ("#.00");
	System.out.println (Df.format (number)); /** * String.Format Print easiest/public static void Numberformat_2 () {System.out.println String.Format ("%.2f", numb
	ER));
		public static void Numberformat_3 () {NumberFormat NF = numberformat.getnumberinstance ();
		Nf.setmaximumfractiondigits (2);
	System.out.println (Nf.format (number));
        public static void Numberformat_4 () {BigDecimal MBD = new BigDecimal (number); Double f1 = Mbd.setscale (2, bigdecimal.round_half_up). DoubLevalue ();
    System.out.println (F1);
 }
}







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.