Handle decimal numbers in mysqli

ε祈祈猫儿з 提交于 2020-07-03 05:52:09

问题


I have to put the price of some items inside a mysql table. When creating the table I'm using DECIMAL(10,2) as I don't need more than 2 digits after the comma (for example: 123,45 would be accepted as an input but 123,456 would be rounded to 123,45 with PHP).

First question: using DECIMAL(10,2), how do I know how many numbers may be stored before the comma? I know it is not 10, as 10 is just the precision Mysql uses when doing math with those numbers: so where the length of the number itself is specified?

Second question: I'm using PHP to round user input to fit the data type (float with 2 numbers after the comma). How should I use mysqli->bind_param to insert those data? Which of these datatypes (from the documentation) accepted by bind_param should I use (and possibly: why)?

Character   Description
i   corresponding variable has type integer
d   corresponding variable has type double
s   corresponding variable has type string
b   corresponding variable is a blob and will be sent in packets

回答1:


DECIMAL(10,2) means that 10 is the maximum number of digits to be used. The 2 specifies that there are two on the right side of the decimal. So this means there are 8 digits left on the left side. See the manual

As for the datatype, you should use double as this is for decimal numbers.

Integer has no decimal chars, so it will floor all numbers. String is for text and not numeric values. Blob is for a binary large object, EG: an image



来源:https://stackoverflow.com/questions/16940263/handle-decimal-numbers-in-mysqli

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!