1

I need your help: does anyone know how I could present a float in Java Card?

The floating point number I need is 0.9. I've heard that I need to use a float point or something like this but I am not really sure.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Jinju
  • 39
  • 1

1 Answers1

5

Just like most Java Card implementations do not feature a 32-bit integer, they do not contain floating point arithmetic either. This however even goes much deeper: the compiled byte code for floating point is not even supported. So in the end you will have to do this yourself or look for vendor support. Note that most smart card CPU cores won't do floating point either, so it would have to be emulated using integer arithmetic.

If you require arithmetic on real numbers for money calculations or similar then you'd best look into fixed-point arithmetic. One trick is to simply perform calculations where each value is multiplied with 100, i.e. do calculations using cents. So then 0.90 times 10 would become 90 times 10. Then - at the terminal - you can simply re-insert the comma.

If you want to do integer calculations (optional but usually not supported), check my X-mas special answer here ... probably a contender for most complex answer on SO when it comes to code. This way you can do 32 bit calculations which you may need to handle any kind of precision (of ~9 decimal digits instead of ~4 that you get with shorts).


If you only need to store a float then simply encode the floating point to bytes, e.g. using DataOutputStream and store the resulting bytes. Or encode a packed BCD and use a byte to represent where the comma needs to be.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263