• Post Reply Bookmark Topic Watch Topic
  • New Topic

data type for dollar?  RSS feed

 
Hydrian Metanroid
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm converting a program which using money.
Actually, My country is not using dollar type, ( we use integer or long for money type)

But the program need to be adopt dollar!!

it has cents as you know

so, in DB I can choose Number(x,2) or Number(x)
means
in java I can use double or long( for cents )

but if I use long type for dollar, I have to do something ( as /100 or *100)

So, I have question, What type do you use for money? ( double or long? )
If you use long type, how do you switch dollar<->cent?


It's a burdonsome to me, (b'cuz I dont have any chance to use dollar type )
Please help me^^
 
Jelle Klap
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although it seems like a good match at first glance, don't use floating point data types to represent currency.
If you absolutely want to know why you shouldn't use floating point data types, a quick google search should provide you with more than enough information.
I'd recommend you go with java.math.BigDecimal instead, in fact so does Sun's Java tutorial.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never use floating-point data types (such as double) for amounts of money.

Floating-point data types have an inherently limited accuracy. If you do calculations with floating-point data types, you are sooner or later going to get rounding errors, and when dealing with money this is almost always unacceptable.

Use an integer data type such as long and calculate everything in cents, and when you need to display an amount simply print a decimal point before the last two digits.

You could also use BigDecimal, which has arbitrary precision.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!