sark9012
sark9012

Reputation: 5747

Pricing issues with pounds and pence!

At the moment I store prices for products in the database as a pence number. So 4321 in the database means £43.21.

Then when reading it out, I divide by 100 to get it in pound and pence format.

However, I have a problem.

If the price is 4320, the returned value is 43.2 without the 0.

How can I get around this?

Thanks!

Upvotes: 0

Views: 912

Answers (4)

Dan Lugg
Dan Lugg

Reputation: 20602

money_format() should do the trick. Alternatively number_format() or the powerful printf().

Upvotes: 1

Jacob
Jacob

Reputation: 43239

<?
  echo money_format("%i", 1234.5) 
  //Output: 1234.50
?>

You can use money_format.

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96266

echo number_format($float, 2, '.', '');

and for pretty printing of large values:

echo number_format($float, 2, '.', ',');

Upvotes: 0

Quentin
Quentin

Reputation: 943697

You can format strings with sprintf

See example 9:

<?php
$money1 = 68.75;
$money2 = 54.35;
$money = $money1 + $money2;
// echo $money will output "123.1";
$formatted = sprintf("%01.2f", $money);
// echo $formatted will output "123.10"
?>

Upvotes: 3

Related Questions