I want to store 3.50 into a mysql table. I have a float that I store it in, but it stores as 3.5, not 3.50. How can I get it to have the trailing zero?
Does it really matter if it stores is as 3.5, 3.50 or even 3.500?
What is really important is how it is displayed after it is retrieved from the db.
Or am I missing something here?
Also don't use a float, use a decimal. Float has all sorts of rounding issue and isn't very big.
Do not store money values as float, use the DECIMAL or NUMERIC type:
Documentation for MySQL Numeric Types
EDIT & clarification:
Float values are vulnerable to rounding errors are they have limited precision so unless you do not care that you only get 9.99 instead of 10.00 you should use DECIMAL/NUMERIC as they are fixed point numbers which do not have such problems.
To store values you can use a DECIMAL(10,2) field, then you can use the FORMAT function:
SELECT FORMAT(`price`, 2) FROM `table` WHERE 1 = 1
Why do you want to store "3.50" into your database? 3.5 == 3.50 == 3.5000 as far as the database is concerned.
Your presentation and formatting of figures/dates/etc should be done in the application, not the database.
If you use DECIMAL or NUMERIC types, you can declare them as for example DECIMAL(18, 2) which would force 2 decimals even if they were 0. Depending on how big values you expect you can change the value of the first parameter.
Binary can't accurately represent floating points with only a limited number of bits. It's not so muuch loss of data but actually conversion errors.. Here's the manual giving examples
You can see this in action in your browser, see for yourself in this code snippet.
<script>
var floatSum = 0;
// add 0.1 to floatSum 10 times
for (var i=0; i<10; i++) {
floatSum += 0.1;
}
// if the repetative adding was correct, the floatSum should be equal to 1
var expectedSum = 10*0.1; // 1
// you can see that floatSum does not equal 1 because of floating point error
document.write(expectedSum + " == " + floatSum + " = " + (expectedSum==floatSum) + "<br />");
// --- using integers instead ---
// Assume the example above is adding £0.10 ten times to make £1.00
// With integers, we will use store money in pence (100 pence (also written 100p) in £1)
var intSum = 0;
// add 0.1 to floatSum 10 times
for (var i=0; i<10; i++) {
intSum += 10;
}
// if the repetative adding was correct, the floatSum should be equal to 1
var expectedSum = 10*10; // 100
// you can see that floatSum does not equal 1 because of floating point error
document.write(expectedSum + " == " + intSum + " = " + (expectedSum==intSum) + "<br />");
document.write("To display as £ instead of pence, we can divide by 100 (presentation only) : £" + intSum/100 + "<br />");
</script>