简体   繁体   中英

How to persist PRICE information using Hibernate

In SQL it is a usual practice to store money amounts in columns of type DECIMAL(10,2) . However when it comes to Hibernate mapping, I'd wish to avoid mapping values to floating point numbers. Is there a way to map column to an integer containing number of cents?

The practice of using a decimal(10,2) for money is terrible. Also, the practice of using a floating point value for money is a monkey technique (as in, only a monkey would think it makes sense to store a fixed point value with a non-exact, floating point number).

Instead, determine the smallest monetary value that you need to store, for example 1/1000 of a euro, and store money as an integral multiple of that value. Continuing this example, the value 2.57 euros would be represented by 2570 in the money column.

Money math should always be performed with integral values.

Side note:

Proof of monkey:

float value1 = .1;
float value2 = .2;
float value3 = value1 + value2;

if (value3 == .3)
    printf ("m1. you are not a monkey");
else
    printf ("m2. you are a monkey.  learn something about floating point representation");

message m1 will never display

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM