java double保留小數點的零的問題,java保留小數點問題

來源:互聯網
上載者:User

標籤:

1.用DecimalFormat格式化,
DecimalFormat df=new DecimalFormat("0.00");

System.out.println(df.format(1.2));
追問
如果非得要使用double類型呢?
提問者評。。。。。。。。。。。。
2.
java中double類型變數保留小數點後兩位的問題
mport java.text.*;

DecimalFormat df=new DecimalFormat(".##");
double d=1252.2563;
String st=df.format(d);
System.out.println(st);

JAVA 保留兩位小數的四種方法


import java.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();      } }JAVA中怎麼實現將一個小數只保留後兩位。
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保留小數點的零的問題,java保留小數點問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.