如何使用php表示浮点数字


How to Present a floating point number using php

我有一个价格数据库,它将数字存储为浮点值。这些都在一个网站上展示。价格可以是格式。

x.x    (e.g. 1.4)  
x.xx   (e.g. 1.99)  
x.xxx  (e.g. 1.299) <-- new price format

我曾经使用字符串格式或%.2f来将价格标准化为小数点后两位,但现在我也需要显示3,但前提是价格是小数点后3位。

e.g.   1.4  would display  1.40
       1.45 would display  1.45
       1.445 would display 1.445

上述格式将是给定输入的期望输出。

使用CCD_ 2显示全部具有3个数字。

e.g.   1.4  would display  1.400     
       1.45 would display  1.450    
       1.445 would display 1.445  

但这不是我想要的——有人知道做以下事情的最佳方法吗。

即,如果任何数字有0个1或2个小数点,则应显示2个小数位如果它有3个或更多的小数位,它应该显示3个小数位

我只需要将其格式化为三个位置,然后修剪最后的0。

$formatted = number_format($value, 3, ".", "");
if (substr($formatted, -1) === "0") $formatted = substr($formatted, 0, -1);

使用这个家伙

number_format($data->price, 0, ',', '.');

http://php.net/manual/en/function.number-format.php

以下是我所做的,因为我需要处理应用程序中的一些特殊情况。

  1. 计算dec位置的数量($price是数据库中的浮动项)
  2. 格式基于使用switch语句的位置计数
  3. 对于小数点后三位以下的所有情况,格式为2(零除外)
  4. 对于所有其他带有3的大小写格式。

    $decimals = strlen(substr(strrchr($price,"."),1));  
    switch ($decimals) {
        case 0: {
           if ($price != 0) {
               $price = number_format($price),2);
           }
           break;
        }
        case 1: {
           $price = number_format($price),2);
           break;
        }
        case 2: {
           $price = number_format($price),2);
           break;
        }
        default: {
           $price = number_format($price),3);    // three dec places all other prices
           break;
        }
    

    }

谢谢你的帮助。。。