欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

double类型精度问题格式设置

程序员文章站 2024-01-28 21:15:58
我们知道double类型在进行处理时会涉及到精度丢失问题比如 double d=100*1.005; 结果d的结果为100.49999999999999 怎么解决这种问题呢,...
我们知道double类型在进行处理时会涉及到精度丢失问题比如

double d=100*1.005;

结果d的结果为100.49999999999999

怎么解决这种问题呢,用DecimalFormat,它对double类型的进行四舍五入处理用法如下:

DecimalFormat df=new DecimalFormat(pattern); 

String nums=df.format(value);

这里给pattern:”.00“

value:100*1.005

nums值为:100.50 

pattern常用的千分号显示:#,##0.00 (为什么个位数用0不用#,因为如果df.format(0),用#的话0显示为空,结果为.00而用0的话显示0.00)

pattern设置可以参考下面:

Symbol Location Localized? Meaning

0 Number Yes Digit

# Number Yes Digit, zero shows as absent

. Number Yes Decimal separator or monetary decimal separator

- Number Yes Minus sign

, Number Yes Grouping separator

E Number Yes Separates mantissa and exponent in scientific notation. Need not be quoted in prefix or suffix.

; Subpattern boundary Yes Separates positive and negative subpatterns

% Prefix or suffix Yes Multiply by 100 and show as percentage

\u2030 Prefix or suffix Yes Multiply by 1000 and show as per mille

¤(\u00A4) Prefix or suffix No Currency sign, replaced by currency symbol. If doubled, replaced by international currency symbol. If present in a pattern, the monetary decimal separator is used instead of the decimal separator.

' Prefix or suffix No Used to quote special characters in a prefix or suffix, for example, "'#'#" formats 123 to "#123". To create a single quote itself, use two in a row: "# o''clock".