Java中常見的幾種四舍五入方法總結
在Java中,四舍五入到特定的小數(shù)位數(shù)是一個常見的需求,可以通過多種方式實現(xiàn)。以下是幾種常見的四舍五入方法及其代碼示例:
1. 使用Math.round()方法
Math.round()
方法可以將浮點數(shù)四舍五入到最接近的整數(shù)。如果你需要四舍五入到特定的小數(shù)位數(shù),可以先將數(shù)字乘以10的n次方(n為你想要保留的小數(shù)位數(shù)),然后使用Math.round()
進行四舍五入,最后再除以10的n次方得到結果。
public class RoundExample { public static void main(String[] args) { double num = 3.14159; int decimalPlaces = 2; // 保留兩位小數(shù) double roundedNum = Math.round(num * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces); System.out.println(roundedNum); // 輸出 3.14 } }
2. 使用BigDecimal類
BigDecimal
類提供了更精確的浮點數(shù)運算能力,包括四舍五入。它的setScale()
方法可以用來設置小數(shù)點后的位數(shù),并可以通過第二個參數(shù)指定舍入模式,例如BigDecimal.ROUND_HALF_UP
代表四舍五入。
import java.math.BigDecimal; import java.math.RoundingMode; public class BigDecimalRoundExample { public static void main(String[] args) { BigDecimal num = new BigDecimal("3.14159"); int decimalPlaces = 2; // 保留兩位小數(shù) BigDecimal roundedNum = num.setScale(decimalPlaces, RoundingMode.HALF_UP); System.out.println(roundedNum); // 輸出 3.14 } }
3. 使用String.format()方法
雖然String.format()
方法主要用于格式化字符串,但它也可以用于四舍五入浮點數(shù)到指定的小數(shù)位數(shù)。該方法不直接改變數(shù)字,而是將其格式化為包含指定小數(shù)位數(shù)的字符串。
public class StringFormatExample { public static void main(String[] args) { double num = 3.14159; String roundedNumStr = String.format("%.2f", num); double roundedNum = Double.parseDouble(roundedNumStr); // 如果需要再次作為double類型使用 System.out.println(roundedNum); // 輸出 3.14 } }
注意,使用String.format()
方法時,結果是一個字符串,如果你需要將其作為浮點數(shù)進行進一步操作,可以使用Double.parseDouble()
將其轉換回double
類型。
4. 使用DecimalFormat類
DecimalFormat
是NumberFormat
的一個具體子類,用于格式化十進制數(shù)。它允許你為數(shù)字、整數(shù)和小數(shù)指定模式。
import java.text.DecimalFormat; public class DecimalFormatExample { public static void main(String[] args) { double num = 3.14159; DecimalFormat df = new DecimalFormat("#.##"); // 保留兩位小數(shù) String roundedNumStr = df.format(num); double roundedNum = Double.parseDouble(roundedNumStr); // 如果需要再次作為double類型使用 System.out.println(roundedNum); // 輸出 3.14 } }
與String.format()
類似,DecimalFormat
的結果也是一個字符串,可以通過Double.parseDouble()
轉換回double
類型。
以上就是在Java中進行四舍五入到特定小數(shù)位數(shù)的幾種常見方法。每種方法都有其適用場景,可以根據(jù)具體需求選擇使用。
總結
到此這篇關于Java中常見的幾種四舍五入方法的文章就介紹到這了,更多相關Java四舍五入方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
logback輸出日志屏蔽quartz的debug等級日志方式
這篇文章主要介紹了logback輸出日志屏蔽quartz的debug等級日志方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08Springboot項目javax.validation使用方法詳解
這篇文章主要介紹了Springboot項目javax.validation使用方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04Spring Boot 中的 Spring Cloud Feign的原
Spring Cloud Feign 是 Spring Cloud 中的一個組件,它可以幫助我們實現(xiàn)聲明式的 REST 客戶,這篇文章主要介紹了Spring Boot 中的 Spring Cloud Feign,需要的朋友可以參考下2023-07-07解決Java導入excel大量數(shù)據(jù)出現(xiàn)內存溢出的問題
今天小編就為大家分享一篇解決Java導入excel大量數(shù)據(jù)出現(xiàn)內存溢出的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06