DecimalFormat格式化数字

本文详细介绍了Java中DecimalFormat类的使用方法,包括如何通过构造方法和applyPattern()方法对数字进行格式化,同时展示了如何设置数字分组和是否允许数字分组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般情况下可以在实例化DecimalFormat对象时传递数字格式,也可以通过DecimalFormat类中的applyPattern()方法来实现数字格式化。

import java.text.*;    //导入支持类java.text
public class DecimalFormatSimpleDemo {
	
	//使用format()方法对数字进行格式化
	static public void SimgleFormat(String pattern, double value){   //创建静态SimgleFormat成员方法
		DecimalFormat myFormat = new DecimalFormat(pattern);        //获取pattern中的数值并赋值给myFormat
		String output = myFormat.format(value);                                  //将数字进行格式化
		System.out.println(value + " "+ pattern + " " + output);            //输出原数值,输出的格式,输出格式化后的值
	}
	
	//使用applyPattern()方法对数字进行格式化
	static public void UseApplyPatternMethodFormat(String pattern, double value){          //创建静态UseApplyPatternMethodFormat成员方法
		DecimalFormat myFormat = new DecimalFormat();               //获取全部数值并赋值给myFormat
		myFormat.applyPattern(pattern);                                            //调用applyPattern()方法对pattern格式化
		System.out.println(value + " " + pattern + " " + myFormat.format(value));              //输出原数值,输出的格式,输出格式化后的值
	}

	public static void main(String[] args) {
		SimgleFormat("###,###.###",123456.789);                          //调用静态SimgleFormat()方法
		SimgleFormat("000000000.###kg",123456.789);                //在数字后加上单位
		SimgleFormat("000000.000",123.78);                                 //按照格式模板格式化数字,不存在的位以0显示
		UseApplyPatternMethodFormat("#.###%",0.789);              //调用静态UseApplyPatternMethodFormat()方法 ,将数字转换为百分数形式
		UseApplyPatternMethodFormat("###.##",123456.789);    //将小数点后格式化为两位
		UseApplyPatternMethodFormat("0.00\u2030",0.789);      //将数字转化为千分数形式
	}
}

setGroupingSize设置数字分组和etGroupingUsed设置不允许数字分组

import java.text.DecimalFormat;
public class DecimalMethod {
	public static void main(String[] args) {
		DecimalFormat myFormat = new DecimalFormat();
		myFormat.setGroupingSize(2);                      //设置数字分组个数为2
		String output = myFormat.format(123456.789);
		System.out.println("将数字以每两个数字分组:" + output);
		myFormat.setGroupingUsed(false);              //设置不允许数字分组
		String output2 = myFormat.format(123456.789);
		System.out.println("不允许数字分组" + output2);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值