Java:使用BigDecimal、NumberFormat和DecimalFormat保留小數

一、代碼和調試結果

1.1 BigDecimal

在這里插入圖片描述

在這里插入圖片描述

在這里插入圖片描述

![在這里插入圖片描述](https://img-blog.csdnimg.cn/direct/fa36749de8124266a730817710fdf737.png)
1.2 DecimalFormat

在這里插入圖片描述

在這里插入圖片描述
在這里插入圖片描述
在這里插入圖片描述

1.3 NumberFormat

在這里插入圖片描述

二、原代碼

BigDecimalUtil.java 代碼

package utils;import java.math.BigDecimal;
import java.math.RoundingMode;public class BigDecimalUtil {// 默認除法運算精度private static final int DEFAULT_DIV_SCALE = 5;/*** 提供精確的加法運算** @param v1* @param v2* @return*/public static double add(double v1, double v2) {BigDecimal b1 = new BigDecimal(v1);BigDecimal b2 = new BigDecimal(v2);return b1.add(b2).doubleValue();}public static String add(String v1, String v2) {BigDecimal b1 = new BigDecimal(v1);BigDecimal b2 = new BigDecimal(v2);return b1.add(b2).toString();}/*** 提供精確的減法運算** @param v1* @param v2* @return*/public static double subtract(double v1, double v2) {BigDecimal b1 = new BigDecimal(v1);BigDecimal b2 = new BigDecimal(v2);return b1.subtract(b2).doubleValue();}public static String substract(String v1, String v2) {BigDecimal b1 = new BigDecimal(v1);BigDecimal b2 = new BigDecimal(v2);return b1.subtract(b2).toString();}/*** 提供精確的乘法運算** @param v1* @param v2* @return*/public static double multiply(double v1, double v2) {BigDecimal b1 = new BigDecimal(v1);BigDecimal b2 = new BigDecimal(v2);return b1.multiply(b2).doubleValue();}public static String multiply(String v1, String v2) {BigDecimal b1 = new BigDecimal(v1);BigDecimal b2 = new BigDecimal(v2);return b1.multiply(b2).toString();}/*** 提供(相對)精確的除法運算,當發生除不盡的情況時,精確到 小數點以后10位,以后的數字四舍五入,舍入模式采用ROUND_HALF_UP** @param v1* @param v2* @return 兩個參數的商*/public static double divide(double v1, double v2) {return divide(v1, v2, DEFAULT_DIV_SCALE);}/*** 提供(相對)精確的除法運算。當發生除不盡的情況時,由scale參數指 定精度,以后的數字四舍五入。舍入模式采用ROUND_HALF_UP** @param v1* @param v2* @param scale*            表示需要精確到小數點以后幾位。* @return 兩個參數的商*/public static double divide(double v1, double v2, int scale) {return divide(v1, v2, scale, RoundingMode.HALF_UP);}/*** 提供(相對)精確的除法運算。當發生除不盡的情況時,由scale參數指 定精度,以后的數字四舍五入。舍入模式采用用戶指定舍入模式** @param v1* @param v2* @param scale*            表示需要精確到小數點以后幾位* @param round_mode*            表示用戶指定的舍入模式* @return 兩個參數的商*/public static double divide(double v1, double v2, int scale, RoundingMode round_mode) {if (scale < 0) {throw new IllegalArgumentException("The scale must be a positive integer or zero");}BigDecimal b1 = new BigDecimal(Double.toString(v1));BigDecimal b2 = new BigDecimal(Double.toString(v2));return b1.divide(b2, scale, round_mode).doubleValue();}/*** 提供(相對)精確的除法運算,當發生除不盡的情況時,精確到 小數點以后10位,以后的數字四舍五入,舍入模式采用ROUND_HALF_EVEN** @param v1* @param v2* @return 兩個參數的商,以字符串格式返回*/public static String divide(String v1, String v2) {return divide(v1, v2, DEFAULT_DIV_SCALE);}/*** 提供(相對)精確的除法運算。當發生除不盡的情況時,由scale參數指 定精度,以后的數字四舍五入。舍入模式采用ROUND_HALF_UP** @param v1* @param v2* @param scale*            表示需要精確到小數點以后幾位* @return 兩個參數的商,以字符串格式返回*/public static String divide(String v1, String v2, int scale) {return divide(v1, v2, scale, RoundingMode.HALF_UP);}/*** 提供(相對)精確的除法運算。當發生除不盡的情況時,由scale參數指 定精度,以后的數字四舍五入。舍入模式采用用戶指定舍入模式** @param v1* @param v2* @param scale*            表示需要精確到小數點以后幾位* @param round_mode*            表示用戶指定的舍入模式* @return 兩個參數的商,以字符串格式返回*/public static String divide(String v1, String v2, int scale, RoundingMode round_mode) {if (scale < 0) {throw new IllegalArgumentException("The scale must be a positive integer or zero");}BigDecimal b1 = new BigDecimal(v1);BigDecimal b2 = new BigDecimal(v2);return b1.divide(b2, scale, round_mode).toString();}/*** 提供精確的小數位四舍五入處理,舍入模式采用ROUND_HALF_EVEN** @param v*            需要四舍五入的數字* @param scale*            小數點后保留幾位* @return 四舍五入后的結果*/public static double round(double v, int scale) {return round(v, scale, RoundingMode.HALF_UP);}/*** 提供精確的小數位四舍五入處理** @param v*            需要四舍五入的數字* @param scale*            小數點后保留幾位* @param round_mode*            指定的舍入模式* @return 四舍五入后的結果*/public static double round(double v, int scale, RoundingMode round_mode) {if (scale < 0) {throw new IllegalArgumentException("The scale must be a positive integer or zero");}BigDecimal b = new BigDecimal(Double.toString(v));return b.setScale(scale, round_mode).doubleValue();}/*** 提供精確的小數位四舍五入處理,舍入模式采用ROUND_HALF_UP** @param v*            需要四舍五入的數字* @param scale*            小數點后保留幾位* @return 四舍五入后的結果,以字符串格式返回*/public static String round(String v, int scale) {return round(v, scale, RoundingMode.HALF_UP);}/*** 提供精確的小數位四舍五入處理** @param v*            需要四舍五入的數字* @param scale*            小數點后保留幾位* @param round_mode*            指定的舍入模式* @return 四舍五入后的結果,以字符串格式返回*/public static String round(String v, int scale, RoundingMode round_mode) {if (scale < 0) {throw new IllegalArgumentException("The scale must be a positive integer or zero");}BigDecimal b = new BigDecimal(v);return b.setScale(scale, round_mode).toString();}
}

TestBigDecimal.java代碼

package test;import utils.BigDecimalUtil;
import utils.PrintlnUtils;import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;public class TestBigDecimal {public static void main(String[] args) {test1();test2();}public static void test1() {BigDecimal a = new BigDecimal("10");BigDecimal b = new BigDecimal("5");BigDecimal c = null;/*RoundingMode.HALF_UP5.5     62.5     31.6     21.1     11.0     1-1.0    -1-1.1    -1-1.6    -2-2.5    -3-5.5    -6------------------------------BigDecimal.ROUND_CEILING5.5         62.5         31.6         21.1         21.0         1-1.0        -1-1.1        -1-1.6        -1-2.5        -2-5.5        -5*///1.加法-add
//          c = a.add(b);//c = 15
//        c = a.add(b).setScale(2,BigDecimal.ROUND_HALF_UP) // 過時了c = a.add(b).setScale(2, RoundingMode.HALF_UP);// 2 表示:保留兩位小數PrintlnUtils.println("c = " + c);//c = 15.00//2.減法-subtractc = a.subtract(b).setScale(2, RoundingMode.HALF_UP);PrintlnUtils.println("c = " + c);// c = 5.00String substract = BigDecimalUtil.substract("10", "5");PrintlnUtils.println("BigDecimalUtil.substract = " + substract);// BigDecimalUtil.substract = 5String substract2 = BigDecimalUtil.substract("10.00", "5");PrintlnUtils.println("BigDecimalUtil.substract = " + substract2);// BigDecimalUtil.substract = 5.00String substract3 = BigDecimalUtil.substract("10.0", "5");PrintlnUtils.println("BigDecimalUtil.substract = " + substract3);// BigDecimalUtil.substract = 5.0String substract4 = BigDecimalUtil.substract("10.0", "5.00");PrintlnUtils.println("BigDecimalUtil.substract = " + substract4);// BigDecimalUtil.substract = 5.00String substract5 = BigDecimalUtil.substract("10", "5.0");PrintlnUtils.println("BigDecimalUtil.substract = " + substract5);// BigDecimalUtil.substract = 5.0//乘法-multiplyc = a.multiply(b).setScale(2, RoundingMode.HALF_UP);PrintlnUtils.println("c = " + c);// c = 50.00//除法-dividec = a.divide(b).setScale(2, RoundingMode.HALF_UP);PrintlnUtils.println("c = " + c);//c = 2.00c = a.divide(new BigDecimal(100), 2, RoundingMode.HALF_UP);PrintlnUtils.println("c = " + c);//c = 0.10//整數舍棄零DecimalFormat df = new DecimalFormat("###.##");String s1 = df.format(new BigDecimal(88.88));String s2 = df.format(new BigDecimal(66.00));String s3 = df.format(new BigDecimal(66.15));String s4 = df.format(new BigDecimal(-66.15));String s5 = df.format(new BigDecimal(666.15));String s6 = df.format(new BigDecimal(666.10));String s7 = df.format(new BigDecimal(666.1));String s8 = df.format(new BigDecimal(666.5));String s9 = df.format(new Double(10666.50));String s92 = df.format(new Double(10666.52));String s93 = df.format(new Double(10666.3));String s94 = df.format(new Double(10666.00));String s95 = df.format(new Double(10666.5));PrintlnUtils.println("s1 = "+s1);//  s1 = 88.88PrintlnUtils.println("s2 = "+s2);//  s2 = 66PrintlnUtils.println("s3 = "+s3);//  s3 = 66.15PrintlnUtils.println("s4 = "+s4);//  s4 = -66.15PrintlnUtils.println("s5 = "+s5);//  s5 = 666.15PrintlnUtils.println("s6 = "+s6);//  s6 = 666.1PrintlnUtils.println("s7 = "+s7);//  s7 = 666.1PrintlnUtils.println("s8 = "+s8);//  s8 = 666.5PrintlnUtils.println("s9 = "+s9);//  s9 = 10666.5PrintlnUtils.println("s92 = "+s92);//  s92 = 10666.52PrintlnUtils.println("s93 = "+s93);//  s93 = 10666.3PrintlnUtils.println("s94 = "+s94);//  s94 = 10666PrintlnUtils.println("s95 = "+s95);//  s95 = 10666.5}public static void test2() {PrintlnUtils.println("test2 ---------------------------------------------------------------------------------------");// BigDecimal// 保留兩位小數System.out.println(new BigDecimal(0.2).setScale(2, RoundingMode.HALF_UP).doubleValue());// 0.2System.out.println(new BigDecimal(0.235).setScale(2, RoundingMode.HALF_UP).doubleValue());// 0.23System.out.println(new BigDecimal(0.2351).setScale(2, RoundingMode.HALF_UP).doubleValue());// 0.24System.out.println(new BigDecimal(42).setScale(2, RoundingMode.HALF_UP).doubleValue());// 42.0PrintlnUtils.println(" ---------------------------------------------------------------------------------------");System.out.println(new BigDecimal(0.2).setScale(2, RoundingMode.HALF_UP));// 0.20System.out.println(new BigDecimal(0.235).setScale(2, RoundingMode.HALF_UP));// 0.23System.out.println(new BigDecimal(0.2351).setScale(2, RoundingMode.HALF_UP));// 0.24System.out.println(new BigDecimal(42).setScale(2, RoundingMode.HALF_UP));// 42.00PrintlnUtils.println(" ---------------------------------------------------------------------------------------");// NumberFormat// 保留兩位小數,個位無數字填充 0NumberFormat nformat  = NumberFormat.getInstance();nformat.setMaximumFractionDigits(2);System.out.println(nformat.format(0.2));// 0.2System.out.println(nformat.format(0.235));// 0.23System.out.println(nformat.format(0.2351));// 0.24System.out.println(nformat.format(42));// 42PrintlnUtils.println(" ---------------------------------------------------------------------------------------");// DecimalFormat,是NumberFormat的具體實現子類// 保留兩位小數,對應位上無數字填充0DecimalFormat df = new DecimalFormat("#0.00");df.setRoundingMode(RoundingMode.CEILING);System.out.println(df.format(0.2));// 0.20System.out.println(df.format(0.235));// 0.23System.out.println(df.format(0.2351));// 0.24, 因為0.2351在0.23-0.24之間,距離0.24更近,所以輸出0.24System.out.println(df.format(42));// 42.00PrintlnUtils.println(" ---------------------------------------------------------------------------------------");DecimalFormat df4 = new DecimalFormat();// #:位置上無數字不顯示df4.applyPattern("#.##");System.out.println(df4.format(345235.0));// 345235System.out.println(df4.format(345235.01245));// 345235System.out.println(df4.format(345235.0156));// 345235System.out.println(df4.format(345235.425));// 345235PrintlnUtils.println(" ---------------------------------------------------------------------------------------");DecimalFormat df42 = new DecimalFormat("0.00");System.out.println(df42.format(345235.0));System.out.println(df42.format(345235.01245));System.out.println(df42.format(345235.0156));System.out.println(df42.format(345235.425));//345235.00//345235.01//345235.02//345235.42PrintlnUtils.println(" ---------------------------------------------------------------------------------------");df42.setRoundingMode(RoundingMode.CEILING);System.out.println(df42.format(345235.0));System.out.println(df42.format(345235.01245));System.out.println(df42.format(345235.0156));System.out.println(df42.format(345235.425));//345235.00//345235.02//345235.02//345235.43PrintlnUtils.println(" ---------------------------------------------------------------------------------------");// 0:位置上無數字顯示0df4.applyPattern("0.00");System.out.println(df4.format(345235.0));// 345235.00System.out.println(df4.format(345235));// 345235.00// 加負數顯示df4.applyPattern("-0.00");System.out.println(df4.format(345235.34567));// -345235.35// 逗號分隔df4.applyPattern("-0,000.00");System.out.println(df4.format(345235.34567));// -345,235.35// 百分位df4.applyPattern("0.00%");System.out.println(df4.format(0.34567));// 34.57%// 千分位df4.applyPattern("0.00\u2030");System.out.println(df4.format(0.34567));// 345.67‰// 科學計數法,E之前是底數的格式,E之后的是指數的格式df4.applyPattern("0.00E00");System.out.println(df4.format(2342.444));// 2.34E03// 格式后面加單位符號df4.applyPattern("0.00 KG");System.out.println(df4.format(2342.444));// 2342.44 KG// 格式前面加單位符號df4.applyPattern("$ 0.00");System.out.println(df4.format(2342.444));// $ 2342.44df4.applyPattern("0.00 QA");System.out.println(df4.format(2342.444));// 2342.44 QA// 使用舍入模式:ROUND_HALF_EVEN,// 保留位數是奇數,使用ROUND_HALF_DOWN// 保留位數是偶數,使用ROUND_HALF_UP
//        df4.setRoundingMode(RoundingMode.HALF_UP);System.out.println(df4.format(2342.435));// 2342.43 QASystem.out.println(df4.format(2342.445));// 2342.45 QA// String.format// 保留兩位小數,個位數及小數點后兩位無數字填充0,四舍五入System.out.println(String.format("%.2f", 0.2));// 0.20System.out.println(String.format("%.2f", 0.235));// 0.24System.out.println(String.format("%.2f", 0.236));// 0.24System.out.println(String.format("%.2f", 42.0));// 42.00}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/13048.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/13048.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/13048.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

前端模塊導入導出方式

不同的導出方式和相應的導入方式&#xff0c;可以提煉成 3 種類型&#xff1a;name、default 和 list。 以下是使用示例&#xff1a; // Name Export | Name Import // 一個“命名”的導出 export const name value import { name } from ...? 錯誤示例&#xff1a; export…

Linux平臺和Windows平臺互傳文件

rz和sz的出發對象都是從Linux出發的&#xff0c;例如sz發送&#xff08;Send&#xff09;從Linux->發送到Windows。 rz 從Windows文件發送到Linux中 先創立一個新文本文件 之后將hello Windows輸入到該文本文件中 在顯示器上顯示里面是否有hello Windows內容 sz發送Lin…

Flutter 中的 PageStorage 小部件:全面指南

Flutter 中的 PageStorage 小部件&#xff1a;全面指南 在Flutter中&#xff0c;PageStorage小部件提供了一種方法來保存和恢復頁面間的信息&#xff0c;這對于具有多個頁面且需要在這些頁面之間共享狀態的應用程序非常有用。本文將詳細介紹PageStorage的用途、如何使用它以及…

Microsoft Azure AI語音服務

一&#xff1a;文字轉語音SDK安裝 安裝語音 SDK - Azure AI services | Microsoft Learn 二&#xff1a;基于文本轉語音Rest API 文本轉語音 API 參考 (REST) - 語音服務 - Azure AI services | Microsoft Learn 三&#xff1a;基于文本合成語音 如何基于文本合成語音 - 語…

Retrying,一個神奇優雅的 Python 庫

大家好&#xff01;我是愛摸魚的小鴻&#xff0c;關注我&#xff0c;收看每期的編程干貨。 一個簡單的庫&#xff0c;也許能夠開啟我們的智慧之門&#xff0c; 一個普通的方法&#xff0c;也許能在危急時刻挽救我們于水深火熱&#xff0c; 一個新穎的思維方式&#xff0c;也許能…

非成對意象翻譯中的內容制約范式再思考

Rethinking the Paradigm of Content Constraints in Unpaired Image-to-Image Translation 非成對意象翻譯中的內容制約范式再思考 Xiuding Cai1 2, Yaoyao Zhu1 2, Dong Miao1 2, Linjie Fu1 2, Yu Yao1 2 蔡秀定 1 2 、朱瑤瑤 1 2 、苗東 1 2 、付林杰 1 2 、余瑤 1 2 Corre…

遙感數據集制作(Potsdam數據集為例):TIF圖像轉JPG,TIF標簽轉PNG,圖像重疊裁剪

文章目錄 TIF圖像轉JPGTIF標簽轉PNG圖像重疊裁剪圖像重命名數據集轉COCO格式數據集轉VOC格式 遙感圖像不同于一般的自然圖像&#xff0c;由于波段數量、圖像位深度等原因&#xff0c;TIF圖像數據不能使用簡單的格式轉換方法。本文以Potsdam數據集為例&#xff0c;制作能夠直接用…

Linux安裝配置CGAL,OpenCV和Gurobi記錄

安裝Qt&#xff0c;查看當前的Qt版本&#xff0c;需要至少滿足v5.12 qmake -v安裝CGAL&#xff0c;The Computational Geometry Algorithms Library (cgal.org) CGAL v5.6.1&#xff1a;https://github.com/CGAL/cgal/releases/download/v5.6.1/CGAL-5.6.1.tar.xz 確保C編譯…

每日復盤-20240515

僅用于記錄當天的市場情況&#xff0c;用于統計交易策略的適用情況&#xff0c;以便程序回測 短線核心&#xff1a;不參與任何級別的調整&#xff0c;采用龍空龍模式 一支股票 10%的時候可以操作&#xff0c; 90%的時間適合空倉等待 國聯證券 (1)|[9:25]|[133765萬]|31.12 一…

基于Pytorch深度學習神經網絡MNIST手寫數字識別系統源碼(帶界面和手寫畫板)

第一步&#xff1a;準備數據 mnist開源數據集 第二步&#xff1a;搭建模型 我們這里搭建了一個LeNet5網絡 參考代碼如下&#xff1a; import torch from torch import nnclass Reshape(nn.Module):def forward(self, x):return x.view(-1, 1, 28, 28)class LeNet5(nn.Modul…

【數據結構】C++語言實現二叉樹的介紹及堆的實現(詳細解讀)

c語言中的小小白-CSDN博客c語言中的小小白關注算法,c,c語言,貪心算法,鏈表,mysql,動態規劃,后端,線性回歸,數據結構,排序算法領域.https://blog.csdn.net/bhbcdxb123?spm1001.2014.3001.5343 給大家分享一句我很喜歡我話&#xff1a; 知不足而奮進&#xff0c;望遠山而前行&am…

分布式系統的一致性與共識算法(三)

順序一致性(Sequential Consistency) ZooKeeper 一種說法是ZooKeeper是最終一致性&#xff0c;因為由于多副本、以及保證大多數成功的ZAB協議&#xff0c;當一個客戶端進程寫入一個新值&#xff0c;另外一個客戶端進程不能保證馬上就能讀到這個值&#xff0c;但是能保證最終能…

我的第一個網頁:武理天協

1. html代碼 1.1 首頁.html <!DOCTYPE html> <html lang"zh"> <head><meta charset"UTF-8"><title>武理天協</title><link rel"stylesheet" href"./style.css"><link rel"stylesh…

【車載開發系列】SID$11服務配置

【車載開發系列】SID$11服務配置 前言 ECUReset(ECU重置),ECU作為Server端,執行Client發送來ECU Reset請求中重啟的類型(通過子服務區分)。對于UDS協議關于處理該請求的邏輯,沒有強制性定義。 Step1:SID和SubFunction的追加 BasicEditor→Dcm→DcmConfigSet→DcmDs…

vs2019 c++里用 typeid() . name () 與 typeid() . raw_name () 測試數據類型的區別

&#xff08;1&#xff09; 都知道&#xff0c;在 vs2019 里用 typeid 打印的類型不大準&#xff0c;會主動去掉一些修飾符&#xff0c; const 和引用 修飾符會被去掉。但也可以給咱們驗證學到的代碼知識提供一些參考。那么今天發現其還有 raw_name 成員函數&#xff0c;這個函…

AES分組密碼

一、AES明文和密鑰位數 RIJNDAEL 算法數據塊長度和密鑰長度都可獨立地選定為大于等于 128 位且小于等于 256 位的 32 位的任意倍數。 而美國頒布 AES 時卻規定數據塊的長度為 128 位、密鑰的長度可分別選擇為 128 位&#xff0c; 192 位或 256 位 1.1 狀態 中間結果叫做狀態…

建模:3dmax

3Dmax 制作模型和動畫&#xff08;橘肉&#xff09;&#xff1b; RizomUV 對模型進行展UV&#xff08;橘皮&#xff09;&#xff1b; Substance Painter 紋理手繪&#xff08;給橘皮制定想要的皮膚&#xff09;&#xff1b; 1.基礎 1.1可編輯多邊形、可編輯樣條線 體、面都需要…

Polylang Pro插件下載:多語言網站構建的終極解決方案

在全球化的今天&#xff0c;多語言網站已成為企業拓展國際市場的重要工具。然而&#xff0c;創建和管理一個多語言網站并非易事。幸運的是&#xff0c;Polylang Pro插件的出現&#xff0c;為WordPress用戶提供了一個強大的多語言解決方案。本文將深入探討Polylang Pro插件的功能…

linux上git 使用方法

一、git上新建倉庫 在git上新建倉庫&#xff0c;并命名 二、本地初始化 //命令行 ssh-keygen -t rsa -b 4096 -C "your_emailexample.com" //ssh查看 cd /root/.ssh/ vim rsa.pub //復制后粘貼進git網頁設置里的ssh key //測試設置是否成功 ssh -T gitgithub.com/…

暴力數據結構之二叉樹(堆的相關知識)

1. 堆的基本了解 堆&#xff08;heap&#xff09;是計算機科學中一種特殊的數據結構&#xff0c;通常被視為一個完全二叉樹&#xff0c;并且可以用數組來存儲。堆的主要應用是在一組變化頻繁&#xff08;增刪查改的頻率較高&#xff09;的數據集中查找最值。堆分為大根堆和小根…