3

If variable A = 0.07 when echoed and variable B = 2100.00 when echoed

if we: $c = $a * $b;

when the end result is a whole # ( i.e. $c = 147) is there any way to force the result to keep 2 decimal places and hold the trailing zero's so that ( $c = 147.00 ) ??

I have tried the following but the result still reported a whole number without trailing zero's:

$c = round($c,2);

So what obvious thing am i missing here?

DMSJax
  • 1,709
  • 4
  • 22
  • 35

3 Answers3

4

Have a look at PHP's number_format() function. You could do:

$cStr = number_format($c, 2);

to get a string with two decimal points. Note that the result of number_format() is a string, not a number

Filippos Karapetis
  • 4,367
  • 21
  • 39
  • 2
    Or `printf("%.2f", $number)` (might be more convenient if you're just going to print it anyway) – nice ass Jun 22 '13 at 01:19
  • Well this does work but you said the result is a string and not a number. This is all pre-processing in a e-cart before being transmitted to a payment gateway. Passing the result to the gateway as a string vs a number shouldn't matter should it? – DMSJax Jun 22 '13 at 01:29
  • How are you passing this to the gateway? – Filippos Karapetis Jun 22 '13 at 01:34
  • It will pass to gateway as a $_POST value, i was testing what you had and it won't work that way. The result of the code below is 2 when it should be 2000.00. I cant pass that to the payment gateway as it would be wrong $2 vs $2000: `$a=1000.00; $b=1000.00; $a = number_format($a,2); $b = number_format($b,2); echo $a; echo "
    "; echo $b; $c = $a+$b; echo "
    ".$c;`
    – DMSJax Jun 22 '13 at 01:42
1

If you want to format a number as a string, you should use number_format()

$c_string = number_format($c, 2);
jeroen
  • 91,079
  • 21
  • 114
  • 132
0

There is no way to force the variable to have 2 decimal positions. You can use number_format() to force on display though.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358