Java double retains the 0 decimal point problem, java reserved decimal point problem

Source: Internet
Author: User

1. Format with DecimalFormat,
DecimalFormat df=new DecimalFormat ("0.00");

System.out.println (Df.format (1.2));
Ask
What if I have to use a double type?
The questioner comments on .....
2.
double-type variable in Java preserves two decimal points
Mport java.text.*;

DecimalFormat df=new DecimalFormat (". # #");
Double d=1252.2563;
String St=df.format (d);
System.out.println (ST);

JAVA four ways to keep two decimal places


importjava.math.BigDecimal;
import java.text.DecimalFormat; import java.text.NumberFormat; public class format {      double f =  111231.5585 ;      public void m1() {          BigDecimal bg =  new BigDecimal(f);          double f1 = bg.setScale( 2 , BigDecimal.ROUND_HALF_UP).doubleValue();          System.out.println(f1);      }      /**       * DecimalFormat转换最简便       */      public void m2() {          DecimalFormat df =  new DecimalFormat( "#.00" );          System.out.println(df.format(f));      }      /**       * String.format打印最简便       */      public void m3() {          System.out.println(String.format( "%.2f" , f));      }      public void m4() {          NumberFormat nf = NumberFormat.getNumberInstance();          nf.setMaximumFractionDigits( 2 );          System.out.println(nf.format(f));      }      public static void main(String[] args) {          format f =  new format();          f.m1();          f.m2();          f.m3();          f.m4();      } } How does Java implement to keep a small number only after two bits.
Import Java.text.NumberFormat;
public class Testnumberformat {
public static void Main (string[] args) {
NumberFormat NF = numberformat.getinstance ();
Nf.setmaximumfractiondigits (2);
Double var = 8.88888;
System.out.println (Nf.format (Var));
}
}

Java double retains the 0 decimal point problem, java reserved decimal point problem

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.