1

Suppose we have a BigDecimal variable setted up like this, and we can't change the way of it's creation:

BigDecimal num = new BigDecimal(6.0053);

So we'll see the following 'pretty' value after an output:

System.out.println(num);   //0053000000000000824229573481716215610504150390625

The only way I've found to resolve this problem was using BigDecimal.valueOf():

System.out.println(BigDecimal.valueOf(num.doubleValue()));   //6.0053

But is there a more simple solution?

Thanks in advance.

XpressOneUp
  • 195
  • 10
  • Don't use the `new BigDecimal(double)` constructor - it creates unprecise values: http://stackoverflow.com/questions/3829029/how-to-convert-from-float-to-bigdecimal-in-java – Natix Jan 31 '14 at 13:25
  • 2
    Well the underlying problem is with the value, which doesn't represent what you want it to represent. You say you can't change the way it's created, but you should really focus on that, as that's where the problem started. Anything else is just papering over the cracks. – Jon Skeet Jan 31 '14 at 13:25
  • 1
    @Natix: No, it creates perfectly precise values - just not the values you might expect. I disagree with the documentation about "unpredictability" here - the result is predictable, but you need to understand what's going on first. – Jon Skeet Jan 31 '14 at 13:26
  • Thanks Jon, I know that the problem is with creation, and was only interested in some quick and dirty workaround. – XpressOneUp Jan 31 '14 at 13:33

4 Answers4

3

Use java.text.DecimalFormat to format the numbers.

NumberFormat format = new DecimalFormat("0.####");
System.out.println(format.format(num));

The format options can be found here

Peter Walser
  • 15,208
  • 4
  • 51
  • 78
  • I bet it wouldn't be simpler than BigDecimal.valueOf(num.doubleValue()). I was wondering are there any very simple solutions? – XpressOneUp Jan 31 '14 at 13:25
  • @XpressOneUp No indeed, and this poster hasn't claimed otherwise, but it will also provide a specific number of decimal places, and avoid scientific notation, and various other things you probably need but may not know about yet. Your choice. – user207421 Jan 31 '14 at 13:26
2
BigDecimal num = new BigDecimal(6.0053);
DecimalFormat df=new DecimalFormat("0.0000");
System.out.println(df.format(num));
Dima
  • 8,586
  • 4
  • 28
  • 57
1
System.out.println(new DecimalFormat("###,##0.00").format(myBigDecimalVariable));
Mateus Viccari
  • 7,389
  • 14
  • 65
  • 101
1

You can use String.format with the "g" formatting type. It allows you to control how many digits you want, etc. See here for all formatting options.

BigDecimal num = new BigDecimal(6.0053);
String formated = String.format("%6.5g", num);
System.out.println(formated);

(Result : 6.0053)

Olivier Croisier
  • 6,139
  • 25
  • 34