數(shù)字的格式化在解決實際問題時使用非常普遍,如顯示某超市的商品價格,需要保留兩位小數(shù)。Java 主要對浮點型數(shù)據(jù)進(jìn)行數(shù)字格式化操作,其中浮點型數(shù)據(jù)包括 double 和 float 型數(shù)據(jù),在 java 中常用以下方法:
目錄
? ? ? ?// 方法一 :DecimalFormat轉(zhuǎn)換最簡便 #.00 表示兩位小數(shù)
? ? ? // 方法二:模仿C語言的輸出方式
? ? ? ?// 方法三 String.format打印最簡便
? ? ? ?// 方法四 商業(yè)計算中中提供精確計算
? ? ?// 方法五 使用格式化數(shù)字類 NumberFormat
1. 使用DecimalFormat和BigDecimal格式化數(shù)字
2. 使用String.format("%.2f",dbstr)
以下程序中使用5種方式來保留小數(shù)位數(shù)
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DecimalFormatDemo {
? ? ? ? public static void main(String[] args) {
? ? ? ? double data = 111231.4585;
? ? ? ?// 方法一 :DecimalFormat轉(zhuǎn)換最簡便 #.00 表示兩位小數(shù)
? ? ? DecimalFormat df = new DecimalFormat("#.00");
? ? ? System.out.println(df.format(data));
? ? ? // 方法二:模仿C語言的輸出方式
? ? ? System.out.printf("%.2f\n", data);
? ? ? ?// 方法三 String.format打印最簡便
? ? ? // %.2f %.表示 小數(shù)點前任意位數(shù)? 2 表示兩位小數(shù)? 格式后的f表示浮點型
? ? ? System.out.println(String.format("%.2f", data));
? ? ? ?// 方法四 商業(yè)計算中中提供精確計算
? ? ?BigDecimal bg = new BigDecimal(data);
? ? ?double f1 = bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
? ? ?System.out.println(f1);
? ? ?// 方法五 使用格式化數(shù)字類 NumberFormat
? ? ?// 使用 getInstance 或 getNumberInstance 來獲取常規(guī)數(shù)值格式。
? ? ? NumberFormat nf = NumberFormat.getNumberInstance();
? ? ? // 設(shè)置顯示的數(shù)字位數(shù) 為格式化對象設(shè)定小數(shù)點后的顯示的最多位,顯示的最后位四舍五入
? ? ? nf.setMaximumFractionDigits(2);
? ? ? ?nf.setGroupingUsed(false); //去掉千分位符號? ?true則顯示千分位符號
? ? ? ? System.out.println(nf.format(data));
? ? }
}文章來源:http://www.zghlxwxcb.cn/news/detail-588815.html
轉(zhuǎn)自老師課件文章來源地址http://www.zghlxwxcb.cn/news/detail-588815.html
到了這里,關(guān)于java中的數(shù)字的格式化(超詳細(xì))的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!