• 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
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Unpredicatable rounding decimals using Number Format/ Decimal Format

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

The below code is used to round upto two digits after decimal.
1.215 is rounded to 1.22(correct)
1.225 is rounded to 1.22(incorrect)
1.235 is rounded to 1.24(correct)
1.245 is rounded to 1.24(incorrect)


Output:
***1.215***
Rounding using Decimal Formatting:1.22
Rounding using Number Formatting:1.22
***1.225***
Rounding using Decimal Formatting:1.22
Rounding using Number Formatting:1.22
***1.235***
Rounding using Decimal Formatting:1.24
Rounding using Number Formatting:1.24
***1.245***
Rounding using Decimal Formatting:1.24
Rounding using Number Formatting:1.24

Please let me know the behavior of formatting .
Thanks in Advance.

Cheers
>
 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you take a look at the DecimalFormat API, you'll see that is uses BigDecimal#ROUND_HALF_EVEN to do the rounding. Check what ROUND_HALF_EVEN means, and everything's going to be clear, and predictable.
 
Aparna Reguri
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It worked
Thanks a lot

 
Time flies like an arrow. Fruit flies like a banana. Steve flies like a tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic