• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

rounding issue with BigDecimal

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am having a rounding issue when using BigDecimal. When i try to round a number to one decimal place, i.e. 3.65 to be rounded to one decimal place, I get the result as 3.6 and not 3.7 ... Any ideas?

This is my code:

public String formatData(double value, int decimalPlaces) {

try {
java.math.BigDecimal bd = new java.math.BigDecimal(value);
value = bd.setScale(decimalPlaces, java.math.BigDecimal.ROUND_HALF_UP).doubleValue();
java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
String num = nf.format(value);
int decimalIndex = num.indexOf(".");
int addDecimal = num.length() - decimalIndex;
if(decimalIndex == -1 ) {
num = num.concat(".");
for(int i = 0; i < decimalPlaces; i++)
num = num.concat("0");
}
else if(addDecimal <= decimalPlaces) {
for( int i = addDecimal; i <= decimalPlaces; i++)
num = num.concat("0");
}
return (num);
} catch (java.lang.Exception ge) {}
return ("");
}
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why not make it easy on yourself and use Math.round()? There's something wrong with your indexing, because 3.651 rounds to 3.7 but 3.65 doesn't.
 
Darin Niard
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Edit: Although, mine won't put 0s on the end. Seems unnecessary, but that wouldn't be too hard to add. Check out the DecimalFormat class.

Edit2: Upon further inspection, BigDecimal.ROUND_HALF_UP does not seem to be working the way it should.
[ June 24, 2004: Message edited by: Darin Niard ]
 
Vishal Dharod
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanx a lot Darin, you code worked!
 
reply
    Bookmark Topic Watch Topic
  • New Topic