Should I store a field PRICE as an int or as a float int the database?

后端 未结 4 768
小蘑菇
小蘑菇 2021-02-20 03:21

In a previous project, I noticed that the price field was being stored as an int, rather than as a float. This is done by multiplying the actual value by 100, the reason being

相关标签:
4条回答
  • 2021-02-20 03:48

    Interesting question.

    I wouldn't actually choose float in the mysql environment. Too many problems in the past with precision with that datatype.

    To me, the choice would be between int and decimal(18,4).

    I've seen real world examples integers used to represent floating point values. The internals of JD Edwards datatables all do this. Quantities are typically divided by 10000. While I'm sure it's faster and smaller in-table, it just means that we're always having to CAST the ints to a decimal value if we want to do anything with them, especially division.

    From a programming perspective, I'd always prefer to work with decimal for price ( or money in RDBMSs that support it ).

    0 讨论(0)
  • 2021-02-20 03:55

    Floating point errors could cause you problems if you are multiplying large numbers. In general, financial calculations should never be done with floating point numbers where possible.

    0 讨论(0)
  • 2021-02-20 04:00

    I think Decimal is good for this use.

    0 讨论(0)
  • 2021-02-20 04:01

    While it would save you float-related issues, having prices saved as integers might lead to a problem where you end up charging 100 times the price to a customer. It could also confuse other programmers.

    I have seen both solution used successfully on medium-size ecommerce websites, but my preference goes to using floats.

    0 讨论(0)
提交回复
热议问题