JAVA保留小數點位數


/**
 * java 如何保留指定位數的小數
 * @author Administrator
 *
 */
public class Test04 {
    public static void main(String[] args) {
        //保留小數點位數
        double pi = 3.1415;
        //四舍五入函數
        System.out.println(Math.round(3.5));
        
        //取值范圍小的,和取值范圍大的做運算,整個表達式會被提升成大的數據類型
        //掌握這種方法
        System.out.println(pi*1000);
        System.out.println(Math.round(pi*1000)/1000.0);//結果為3.142
//Math.round(a)為四舍五入方法
DecimalFormat df
= new DecimalFormat(".000"); String str = df.format(pi); //String 轉化為doouble double result2 = Double.parseDouble(str); System.out.println(result2); //String str轉換為double String str2 = String.format("%.3f", pi); double results = Double.parseDouble(str2); System.out.println(results); BigDecimal bd = new BigDecimal(pi); double result4 = bd.setScale(3,BigDecimal.ROUND_HALF_UP).doubleValue(); System.out.println(result4); } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM