code_junkie

How do I round up currency values in Java

Nov 14th, 2011
176
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. BigDecimal result = new BigDecimal("50.5399999").setScale(2, BigDecimal.ROUND_HALF_UP);
  2.  
  3. static long round(double a)
  4.  
  5. double d = 50.539999; // or however many 9's, it doesn't matter
  6. int dollars = (int)d;
  7. double frac = d - dollars;
  8. int cents = (int)((frac * 100) + 0.5);
  9.  
  10. long money = 5054;
  11.  
  12. long cents = money % 100;
  13. long dollars = money / 100; // this works due to integer/long truncation
  14.  
  15. System.out.printf("$%d.%02.d", dollars, cents);
  16.  
  17. double value = .539999;
  18. int result = (int) (value*100);
  19. if(((value*100)%result)>.5)
  20. result++;
  21.  
  22. num = .53999999;
  23. int_num = (int)(num * 100); // cast to integer, however you do it in Java
  24. compare_num = (int_num + 0.5) / 100;
  25.  
  26. dollars_and_cents = round(100*a)/100
  27. cents = (dollars_and_cents-(int)dollars_and_cents)*100
  28.  
  29. double d = 50.539999;
  30. long cents = (long)(d * 100 + 0.5);
  31. double rounded = cents/100;
Add Comment
Please, Sign In to add comment