I have just created a database with phpmyadmin and made some pages to view edit and add to this database. One of the field is for money so needs to be to 2 decimal places it is set to a float, but when I enter say 1.20
and add it using the add record page I created and then go back to view it to is says 1.2
does any one know if I have to change any thing the web pages or the data base.
Asked
Active
Viewed 243 times
-1

ErasmoOliveira
- 1,416
- 2
- 20
- 40

Jhondoe
- 101
- 3
-
4do **NOT** use floats for money values. if you want to store money, then use `decimal`, or convert your money into cents and use an int. – Marc B Feb 19 '15 at 15:59
-
Look at my answer bellow, you might find some good pratices. :) – william.eyidi Feb 19 '15 at 16:21
-
@MarcB thanks this work but had to change it to `2,2` can you post as a answer so that i can expect it – Jhondoe Feb 19 '15 at 16:21
-
@Jhondoe I posted the solution you are looking for. cheers `bcdiv()` – william.eyidi Feb 19 '15 at 16:24
-
don't forget to validate the answer, cheers :) – william.eyidi Feb 24 '15 at 18:30
2 Answers
1
Try this example to format numbers
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00

ErasmoOliveira
- 1,416
- 2
- 20
- 40
-
-
@Jhondoe use in .php file, while printing the value in view, not in phpmyadmin. – ErasmoOliveira Feb 19 '15 at 16:10
0
you can use Number_format()
with the precision 2
, and a separator .
with this syntax
echo number_format((float) $number, $precision, '.', '');
as shown on this question: link
it provides a very good demo
IMPROVEMENT
For money transaction it is better to save all the numbers in INT
format then convert them into cents once you want to output them you just divide by Hundred.
Illustration:
1.20
is saved as 120
then when it comes to output you just divide by 100 with the function bcdiv() as follow.
echo bcdiv('120', '100', 2);
result
1.20

Community
- 1
- 1

william.eyidi
- 2,315
- 4
- 27
- 39