Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

java - Format of BigDecimal number

BigDecimal val = BigDecimal.valueOf(0.20);
System.out.println(a);

I want to store in val a value 0.20 and not 0.2. What I can do ?

I dont think I can use NumberFormat in this case, when I use NumberFormat I must know what the length of my decimal number is! I can have 0.20 or 0.5000, I don't know the exact length of my decimal number, so I cannot use :

DecimalFormat df = new DecimalFormat("#0.00");

or

DecimalFormat df = new DecimalFormat("#0.00000");

maybe I have just 2 numbers after point or 5 numbers or more, and this program doesn't work:

 BigDecimal a = BigDecimal.valueOf(0.20);//i give an example of 0.2 i can have 0.98...0
         System.out.println(a);

         NumberFormat nf1 = NumberFormat.getInstance();
         System.out.println(nf1.format(0.5000));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

BigDecimal remembers the trailing zeros - with some significant side-effect:

BigDecimal bd1 = new BigDecimal("0.20"); 
BigDecimal bd2 = new BigDecimal("0.2");

System.out.println(bd1);
System.out.println(bd2);
System.out.println(bd1.equals(bd2));

will print

0.20
0.2
false

And we need to remember, that we can't use BiGDecimal for numbers, where the decimal expansion has a period:

BigDecimal.ONE.divide(new BigDecimal(3));

will throw an exception (what partially answers your concerns in your comments)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...