我是靠谱客的博主 想人陪背包,这篇文章主要介绍java 保留几位小数,现在分享给大家,希望可以做个参考。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.clzhang.sample; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.NumberFormat; public class DoubleTest { /** * 保留两位小数,四舍五入的一个老土的方法 * @param d * @return */ public static double formatDouble1(double d) { return (double)Math.round(d*100)/100; } /** * The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format conversion. * @param d * @return */ public static double formatDouble2(double d) { // 旧方法,已经不再推荐使用 // BigDecimal bg = new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP); // 新方法,如果不需要四舍五入,可以使用RoundingMode.DOWN BigDecimal bg = new BigDecimal(d).setScale(2, RoundingMode.UP); return bg.doubleValue(); } /** * NumberFormat is the abstract base class for all number formats. * This class provides the interface for formatting and parsing numbers. * @param d * @return */ public static String formatDouble3(double d) { NumberFormat nf = NumberFormat.getNumberInstance(); // 保留两位小数 nf.setMaximumFractionDigits(2); // 如果不需要四舍五入,可以使用RoundingMode.DOWN nf.setRoundingMode(RoundingMode.UP); return nf.format(d); } /** * 这个方法挺简单的。 * DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. * @param d * @return */ public static String formatDouble4(double d) { DecimalFormat df = new DecimalFormat("#.00"); return df.format(d); } /** * 如果只是用于程序中的格式化数值然后输出,那么这个方法还是挺方便的。 * 应该是这样使用:System.out.println(String.format("%.2f", d)); * @param d * @return */ public static String formatDouble5(double d) { return String.format("%.2f", d); } public static void main(String[] args) { double d = 12345.67890; System.out.println(formatDouble1(d)); System.out.println(formatDouble2(d)); System.out.println(formatDouble3(d)); System.out.println(formatDouble4(d)); System.out.println(formatDouble5(d)); } }

DecimalFormat df = new DecimalFormat("#.00"); 当小数为0开头时,比如 0.12678 ,有问题,结果为 .13,0没了。不用此方式。

最后

以上就是想人陪背包最近收集整理的关于java 保留几位小数的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(77)

评论列表共有 0 条评论

立即
投稿
返回
顶部