在mysqli中处理小数 [英] Handle decimal numbers in mysqli
问题描述
我必须将某些项目的价格放入mysql表中.创建表时,我使用的是DECIMAL(10,2)
,因为我不需要在逗号后加上两位以上的数字(例如:123,45将被接受为输入,但是123,456将被四舍五入为123,45).
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).
第一个问题:使用DECIMAL(10,2)
,我如何知道逗号前可以存储多少个数字?我知道它不是10,因为10只是Mysql在对这些数字进行数学运算时使用的精度:那么数字本身的长度在哪里指定?
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?
第二个问题:我正在使用PHP对用户输入进行四舍五入以适应数据类型(逗号后以2个数字浮点).我应该如何使用mysqli->bind_param
插入这些数据?我应该使用(c3>接受的以下哪种数据类型(来自文档)并可能:为什么)?
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
推荐答案
DECIMAL(10,2)
表示10
是要使用的最大位数. 2
指定小数点右边有两个.因此,这意味着左侧还有8
个数字.参见手册
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
对于数据类型,应使用double
,因为这是十进制数字.
As for the datatype, you should use double
as this is for decimal numbers.
Integer
没有小数点字符,因此它将限制所有数字. String
用于文本而不是数字值. Blob
用于二进制大对象EG:图像
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
这篇关于在mysqli中处理小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!