-3
Double amount = 0.001

but amount value is set to 0.0010

we have strict condition at the end to allow only 3 decimal places before storing in DB. but somehow it is appending 0 at the end.

i have tried

 DecimalFormat decimalFormat = new DecimalFormat("#.###");
 String formatedString = decimalFormat.format(amount));

at this point formatedString in 0.001 which is correct. but if i change back again to Double.

Double.valueOf(decimalFormat.format(formatedString));

it is again adding 0 at the end 0.0010. how to remove 0 at the end by default for type Double?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Manjunath
  • 111
  • 1
  • 8

2 Answers2

1

As far as the Double is concerned, 0.001 and 0.0010 is the same thing. If you are storing that in the DB as double, then everything is fine and what you should be looking at is the formatting of whatever program you use to display the values.

kutschkem
  • 7,826
  • 3
  • 21
  • 56
  • My requirement is if user enters 0.0011 it should throw error instead of saving. but for 0.001 it should accept. – Manjunath Mar 27 '18 at 11:47
  • @Manjunath Ok then you can use your code from the question (test it!), but don't worry about a trailing zero in your output. Another option is to use BigDecimal instead of double and restrict it to three decimal places. – kutschkem Mar 27 '18 at 11:52
0

You can use the class BigDecimal to define the scale and the rounding mode for your needs. ie:

BigDecimal val = new BigDecimal("1.12345").setScale(4, RoundingMode.HALF_EVEN);
val.doubleValue();

https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html

Paizo
  • 3,986
  • 30
  • 45