DECIMAL(5,3)能否存储999.99?MySQL数值类型疑问咨询
Hey there! Let's clear up this confusion step by step so you can see exactly why your teacher's explanation is correct, and where your understanding went off track.
First, let's recap how MySQL's DECIMAL(p, s) data type is defined:
p(precision): This is the total number of significant digits you can store (this does not include the decimal point or negative sign).s(scale): This is the exact number of digits reserved for the fractional part (to the right of the decimal point).
For DECIMAL(5,3) specifically:
- The scale
3means we must set aside 3 digits for fractions—no more, no less (MySQL will pad shorter fractional values with trailing zeros automatically, like storing0.56as0.560). - The precision
5limits the total number of digits (integer + fractional) to 5. That leaves5 - 3 = 2digits available for the integer part.
Why your 999.99 example doesn't work
You thought 999.99 fits because it has 5 total digits, but here's the problem:
DECIMAL(5,3)requires 3 fractional digits. To make 999.99 fit this rule, you'd have to write it as999.990—now count the significant digits: that's 6 digits total (3 integer, 3 fractional), which exceeds the precision limit of 5.- Even if we ignore the fractional digit requirement for a moment, 3 integer digits plus 3 fractional digits equals 6 digits—way over the 5-digit cap set by
p=5.
Valid values for DECIMAL(5,3)
Any number that stays within the range of -99.999 to 99.999 (with up to 3 decimal places) is allowed. Examples include:
0.56(stored as0.560)-48.1235.2(stored as5.200)78.458
Final takeaway
Your teacher is completely correct. The mix-up came from not realizing that DECIMAL(p,s) reserves s digits exclusively for the fractional part, so the integer portion can only use p - s digits. You can't have 3 integer digits here because that would require more total digits than the precision allows.
内容的提问来源于stack exchange,提问作者Async-Mayeul




