Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

Is this bug or am I missing sth?

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
try to run the following code:
//code starts here
long n16 = 9999999999999999L;//16 9s
BigDecimal bd = new BigDecimal(n16);
System.out.println("n16= " + n16);
System.out.println("bd= " + bd);
System.out.println("bd.longValue= " + bd.longValue());
//code ends here
//the result is
n16= 9999999999999999 #correct
bd= 100000000000000000 #wrong
bd.longValue= 1000000000000000 #wrong
If it's not a bug, how can I safe convert "n16" into a BigDecimal?
thanks.
Jay
 
Jay Feng
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never mind. It's not bug.
In case anybody want to know, here's the reason.
Before the long is converted into a BigDecimal, it has to be converted into a double(implicit cast), where some precision is lost.
"Conversion of an int or a long value to float, or of a long value to double, may lose precision, that is, the result may lose some of the least significant bits of the value; the resulting floating-point value is a correctly rounded version of the integer value, using IEEE 754 round to nearest mode."(Quoted from VM spec).
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Use BigDecimal.valueOf(long) for this. This illustrates the main problem with static factory methods - they're easy to overlook in an API when you're looking for a constructor.
 
Liar, liar, pants on fire! refreshing plug:
create, convert, edit or print DOC and DOCX in Java
https://products.aspose.com/words/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!