开发者

PHP: Modifying prices to look presentable?

开发者 https://www.devze.com 2023-01-12 05:29 出处:网络
We\'ve all seen that stores have nice-looking pricing on their products; \"1.99\", \"209.90\" and so on.

We've all seen that stores have nice-looking pricing on their products; "1.99", "209.90" and so on.

That's easily done as well if you enter prices manually, bu开发者_开发知识库t l et's say that we would have a database which stores prices, that are daily updated according to currency changes. Prices are therefore automatically calculated and will end up looking like "1547,83" which isn't nice at all for the eyes.

How could a function be made in PHP that both rounds prices and adjust them to be "presentable" within set tolerances depending on the size of the prize?

Thanks a lot!


money_format() or number_format() The latter is generally better - despite the name - for currency values

EDIT

Based on Pekka's comments, a combination of number_format() and round() might give what you want:

$value = 1547.83;

echo number_format($value,2),'<br />';
echo number_format(round($value,1),2),'<br />';
echo number_format(round($value,0),2),'<br />';
echo number_format(round($value,0)-0.01,2),'<br />';
echo number_format(round($value,-1),2),'<br />';

gives

1,547.83
1,547.80
1,548.00
1,547.99
1,550.00

EDIT 2

Slightly more fancified, determining the level of rounding based on the actual value:

$value = 1547.83;
$pos = 3 - floor(log10($value));
echo number_format(round($value,$pos)-0.01,2),'<br />';

//  gives 1,547.99

$value = 1547982.83;
$pos = 3 - floor(log10($value));
echo number_format(round($value,$pos)-0.01,2),'<br />';

//  gives 1,547,999.99


It depends on some rules. Do you want to round up or round down? If the price is 1.93, do you want to make it 1,95 or 1,90 or 1,99?.

I think that you only want to round of the cents and not the whole price.

First, define what rounding should be made, what makes sense for me is:

  • x,00 - x,20 ==> (x-1),99
  • x,21 - x,75 ==> x,49 or x,55
  • x,75 - x,99 ==> x,99

Once you defined these rules, it is just a (numerical) transformation. This is not so much a programming challange, imo you should just define the rounding rules.


Are we really at the point where we consider 1.90 and 3.99 to be user friendly.

That is scary. A user friendly equivalent would be 2.00 or 4.00. The .99 ending is a salesman trick to make the user misjudge the price.

1.99 is in no way "nice for the eyes" as you call it.

EDIT

If you want to ,make it nice for the salesman you could do something terrible like :

$newprice = ceil($original_price) - 0.01;
0

精彩评论

暂无评论...
验证码 换一张
取 消