如何使用php呈现浮点数

时间:2014-09-06 19:19:03

标签: php printf

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

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

上述格式将是给定输入的所需输出。

使用%.3f显示所有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个小数位

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

使用这个家伙

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

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

答案 2 :(得分:0)

由于需要应对我在应用程序中遇到的一些特殊情况,我在这里做了。

  1. 计算dec位数($ price是数据库中的浮点数)。
  2. 使用switch语句基于地点计数的格式。
  3. 对于小数点后小于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;
        }
    

    }

  5. 感谢您的帮助...