views:

256

answers:

4

Hi,

I'm just pondering about whether or not it's possible to create one's own data type? So if you need more precision, that's not supported by one of the basic types, you could just "create" your own fullfilling your requierements.

Is that possible and how?

+16  A: 

Take a look at BigDecimal

Immutable, arbitrary-precision signed decimal numbers

And to answer your question - yes, you can crate data types, but they can't be primitive types (like int, double, etc). They have to be classes, just like the case with BigDecimal (and BigInteger)

And a further advice for using the Big* classes - as written, they are immutable. This means that calling add(..) doesn't change the object - it returns a new object that reflects the change. I.e.

BigDecimal dec = BigDecimal.ZERO;
dec.add(new BigDecimal(5)); // nothing happens
dec = dec.add(new BigDecimal(5)); // this works
Bozho
+2  A: 

Sounds like you might be after the BigDecimal class:

http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html

Scobal
+7  A: 

You can't create your own custom value types in Java, if that's what you're asking. You can, of course, create your own reference types - that's what every class in Java is, after all.

But as others have said, BigDecimal (and BigInteger) should be your starting points for numeric types with more precision.

Jon Skeet
+1  A: 

Everything is always possible.

That doesn't mean that somebody hasn't already done it before however, and much more efficiently than you ever will.

BigInteger and BigDecimal is what you're looking for.

Milan Ramaiya