double类型精度问题格式设置
我们知道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" . |