nuvio
nuvio

Reputation: 2625

How to display two decimals in MYSQL/PHP?

I'd like to display £2.00 instead of £2 or £3.50 instead of £3.5.

These number let's say price is defined as DOUBLE in a MySQL database. How can I force MySQL or PHP to display the two decimals?

Many thanks!

Upvotes: 3

Views: 15740

Answers (4)

eggyal
eggyal

Reputation: 125865

The other answers are correct insofar as they will format a value to two decimal places.

However, given the context in your question, a better answer is don't use the DOUBLE datatype - at least, not for this purpose.

Floating-point data types like DOUBLE are approximate and do not represent exact numbers; they are useful for representing continuous quantities like mass or length. With discrete quantities like currency, they can be disastrous, leading to very unexpected results. For such quantities you really should use instead MySQL's fixed-point types like DECIMAL, which enables you to specify the scale (i.e. the number of decimal places to store) and therefore will not require any such formatting or rounding to produce correct currency values.

Upvotes: 5

felixgaal
felixgaal

Reputation: 2423

For MySQL, you can use the format function:

SELECT FORMAT(1.2345, 2);

It will return 1.23

For PHP, you can use number_format in a similar way:

echo number_format(1.2345, 2);

Also printing 1.23

Upvotes: 9

Jeroen
Jeroen

Reputation: 13257

Try this:

echo number_format ($price, 2);

Upvotes: 7

bfavaretto
bfavaretto

Reputation: 71918

number_format and money_format are your friends!

Upvotes: 5

Related Questions