国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java小數位的例子

2019-11-26 15:54:37
字體:
來源:轉載
供稿:網友

方式一:
四舍五入
double   f   =   111231.5585;
四舍五入 保留兩位小數,可以用String的format函數,
方法如下:

復制代碼 代碼如下:

System.out.println(String.format("%.2f", x1));
System.out.println(String.format("%.2f", x2));
 

DecimalFormat轉換最簡便

復制代碼 代碼如下:

public void m2() {
       DecimalFormat df = new DecimalFormat("#.00");
       System.out.println(df.format(f));
}

例:new java.text.DecimalFormat(”#.00″).format(3.1415926)
#.00 表示兩位小數 #.0000四位小數 以此類推…
方式三:
復制代碼 代碼如下:

double d = 3.1415926;
String result = String .format(”%.2f”);
 

%.2f %. 表示 小數點前任意位數   2 表示兩位小數 格式后的結果為f 表示浮點型。
方式四:
此外如果使用struts標簽做輸出的話,有個format屬性,設置為format="0.00"就是保留兩位小數
例如
復制代碼 代碼如下:

<bean:write name="entity" property="dkhAFSumPl"  format="0.00" />

JAVA中保留N位小數的方法,例子 .
復制代碼 代碼如下:

import java.text.DecimalFormat;

public class numberFarmat {
    public static void main(String[] args) {
       double sd = 23.2558896635;

       //第一種方法 10000.0這個小數點后只表示保留小數,和位數沒關系。
       double d1 = (double) (Math.round(sd*10000)/10000.0000000000);
       double d2 = (double) (Math.round(sd*10000)/10000.0);
       System.out.println("4位小數測試:"+d1);
       System.out.println("4位小數測試:"+d2);

       //第二種方法
       DecimalFormat df2  = new DecimalFormat("###.00");
       DecimalFormat df3  = new DecimalFormat("##.000");
       System.out.println("3位小數:"+df3.format(sd));
       System.out.println("2位小數:"+df2.format(sd));

    }
}
 


運行結果如下:
4位小數測試:23.2559
4位小數測試:23.2559
3位小數:23.256
2位小數:23.26

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 平远县| 阳江市| 刚察县| 临湘市| 丹江口市| 家居| 兴宁市| 青海省| 奇台县| 松原市| 柳林县| 巩留县| 南投县| 逊克县| 漳平市| 彰武县| 南雄市| 古蔺县| SHOW| 宣城市| 武穴市| 巴东县| 宁都县| 中方县| 井陉县| 来凤县| 兴文县| 大同县| 宝丰县| 新龙县| 澜沧| 永善县| 鹤庆县| 藁城市| 安丘市| 神农架林区| 密山市| 天长市| 横峰县| 彩票| 望江县|