java 怎样将string 格式化

如题所述

在java中,将浮点数格式化为string,一般使用DecimalFormat。DecimalFormat的用法示例如下:DecimalFormatdf=newDecimalFormat();doubledata=1234.56789;System.out.println("格式化之前的数字:"+data);Stringstyle="0.0";//定义要显示的数字的格式df.applyPattern(style);//将格式应用于格式化器System.out.println("采用style:"+style+"格式化之后:"+df.format(data));style="00000.000kg";//在格式后添加诸如单位等字符df.applyPattern(style);System.out.println("采用style:"+style+"格式化之后:"+df.format(data));//模式中的"#"表示如果该位存在字符,则显示字符,如果不存在,则不显示。style="##000.000kg";df.applyPattern(style);System.out.println("采用style:"+style+"格式化之后:"+df.format(data));//模式中的"-"表示输出为负数,要放在最前面style="-000.000";df.applyPattern(style);System.out.println("采用style:"+style+"格式化之后:"+df.format(data));//模式中的","在数字中添加逗号,方便读数字style="-0,000.0#";df.applyPattern(style);System.out.println("采用style:"+style+"格式化之后:"+df.format(data));//模式中的"E"表示输出为指数,"E"之前的字符串是底数的格式,//"E"之后的是字符串是指数的格式style="0.00E000";df.applyPattern(style);System.out.println("采用style:"+style+"格式化之后:"+df.format(data));//模式中的"%"表示乘以100并显示为百分数,要放在最后。style="0.00%";df.applyPattern(style);System.out.println("采用style:"+style+"格式化之后:"+df.format(data));//模式中的"\u2030"表示乘以1000并显示为千分数,要放在最后。style="0.00\u2030";//在构造函数中设置数字格式DecimalFormatdf1=newDecimalFormat(style);//df.applyPattern(style);System.out.println("采用style:"+style+"格式化之后:"+df1.format(data));下面是总结:格式化之前的数字:1234.56789采用style:0.0格式化之后:1234.6采用style:00000.000kg格式化之后:01234.568kg采用style:##000.000kg格式化之后:1234.568kg采用style:-000.000格式化之后:-1234.568采用style:-0,000.0#格式化之后:-1,234.57采用style:0.00E000格式化之后:1.23E003采用style:0.00%格式化之后:123456.79%采用style:0.00‰格式化之后:1234567.89‰
温馨提示:内容为网友见解,仅供参考
无其他回答