Re: Preserving Decimals
| From: | Zak Greant | Date: | Fri, 16 Jun 2000 21:38:26 +0000 |
| Subject: | Re: Preserving Decimals | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-2102@lists.php.net to get a copy of this message | ||
At 04:03 PM 6/16/00 -0500, Yoed Anis wrote:
Hello, PHP seems to do a funny thing when it adds empty decimals.. it makes them disappear. So if I were to add 5.00 to 4.00 it would display 9, not 9.00 Or if I were to add 4.50 to 3.00 it would display 8.5 not 8.50 I have looked through the archives and my book for a solution to this problem, since I thought it should be quiet common. After all PHP is used in many commerce sites. So what is the simplest way to preserve decimals in a variable?Hello Yeod, Use the printf and sprintf functions to force decimals when outputting variables. For example: $double = 5.00; // Will print 5 print $double . '<br>'; // Will print 5.00 printf ('%0.2f', $double); AFAIK PHP stores all values - regardless of their type - as strings. If a number is not quoted, then it is reduced to its most compact form (by stripping all leading and trailing zeros) before it is used. Try this example to see more clearly what happens: print "005.00 evaluates to: " . 005.00 . '<br>'; print "5.00 evaluates to: " . 5.00 . '<br>'; print "'5.00' evaluates to: " .'5.00' . '<br><br>'; print "5 * 5 evaluates to: " . 5 * 5 . '<br>'; print "5.00 * 5.00 evaluates to: " . 5.00 * 5.00 . '<br>'; print "'5.00' * '5.00' evaluates to: " .'5.00' * '5.00' . '<br>'; HTH, Zak Zak Greant Creative Director Nucleus Information Service Inc. "I am rather like a mosquito in a nudist camp: I know what I ought to do, but I don't know where to begin." - Stephen Bayne