0

I need to make this print a number with two decimal points, I believe I use this piece of code int $decimals = 0 but I don't know where I need to add it.

Here's the code I have:

<?php 
  $tempPrice = str_replace(',',"", $price); //gets rid of "," 
  $tempPrice = substr($tempPrice,2); //removes currency from the front
  $tempPrice = floatval($tempPrice); //converts to double from string

  if($tempPrice > 1000) 
  {
    echo '£' . round(($tempPrice*0.038), 2) . ' per month';
  }
  else 
  {
    echo 'Lease to buy price not available on this product';
  }
 ?>

Thanks

1 Answers1

0

You can use money_format() php function. http://php.net/money_format

for example in your case

<?php 
  $tempPrice = str_replace(',',"", $price); //gets rid of "," 
  $tempPrice = substr($tempPrice,2); //removes currency from the front
  $tempPrice = floatval($tempPrice); //converts to double from string
  // set international format for the en_GB locale
  setlocale(LC_MONETARY, 'en_GB');    
  if($tempPrice > 1000) 
  {
  echo money_format('%i', $tempPrice ) . " per month";// output->"GBP 1,234.56 per month"
  }
  else 
  {
    echo 'Lease to buy price not available on this product';
  }
 ?>

in addition you can just use php number_format() http://php.net/number_format on $tempPrice

echo "£ ". number_format($tempPrice ) . " per month";

by default number_format() english notation is used. You can set your own number of decimal points, decimal point setarator and thousands separator

echo "£ ". number_format($tempPrice, 2, ".", "," ) . " per month"; // for $tempPrice=1203.52 output will be "£ 1,203.56 per month"
  • Hi Peter thanks for helping. The first example prints GBP, is there a way to change this to £? Alternative with the number_format should I change the `. round` to `. number_format`? – Adam Stevens Mar 31 '15 at 10:12
  • First part of your question is answered before here http://stackoverflow.com/questions/9019337/php-money-format-%C2%A3-sign-not-gbp. On the second part... yes change it but check the number_format function to set it to your needs. –  Apr 02 '15 at 06:35