PHP编号:仅在需要时可见小数点

时间:2010-11-06 13:05:46

标签: php string automation integer

我想知道是否存在一些函数来自动格式化一个数字的小数,所以如果我有:

<?php
    // $sql_result["col_number"] == 1,455.75
    number_format ($sql_result["col_number"], 2, ".", "");
    // will return 1455.75

    // $sql_result["col_number"] == 1,455.00
    number_format ($sql_result["col_number"], 2, ".", "");
    // could I get 1455 instead of 1455.00?
?>

所以我的答案是,如果我的数据库中的DECIMAL数据格式仅在圆形时才会以某种方式删除小数?

或者我应该做那样的事情?

<?php
    // $sql_result["col_number"] == 1,455.00
    str_replace(".00", "", (string)number_format ($sql_result["col_number"], 2, ".", ""));
    // will return 1455
?>

11 个答案:

答案 0 :(得分:26)

floatval或简单地转换为浮动

php > echo floatval(7.00);
7
php > echo floatval(2.30);
2.3
php > echo floatval(1.25);
1.25
php > echo floatval(1.125);
1.125

php > echo (float) 7.00;
7
php > echo (float) 2.30;
2.3
php > echo (float) 1.25;
1.25
php > echo (float) 1.125;
1.125

答案 1 :(得分:13)

我实际上认为你的解决方法和任何方法一样好。它简单明了,在这里谈论性能真的没有意义,所以就去吧。

答案 2 :(得分:8)

正如埃米尔说你的好。但是,如果您要从{例如}移除0 7.50我也有一个建议,rtrim()

<?php
    // if $sql_result["col_number"] == 1,455.50
    rtrim(rtrim(number_format($sql_result["col_number"], 2, ".", ""), '0'), '.');
    // will return 1455.5
?>

答案 3 :(得分:7)

我添加文章Remove useless zero digits from decimals in PHP作为一种更好的方法来清除值,如果需要的话,没有宽松小数。

答案 4 :(得分:5)

你也可以使用rtrim(),它可以删除多余的0,在你可能想要保留一个小数位而不是多余的零的情况下。 (例如,4.50变为4.5。)还允许您将小数位数从2更改为任何其他数字。

rtrim(rtrim((string)number_format($value, 2, ".", ""),"0"),".");

// 4.00 -> 4
// 4.50 -> 4.5
// 4.54000000 -> 4.54 (if you're doing more decimal places)

答案 5 :(得分:1)

实际上,我觉得我能想到的最干净的方式是为那些只是寻找这种事情的人做这件事:

( number_format ($sql_result["col_number"], 2) * 100 ) / 100;

答案 6 :(得分:1)

如果您定位美国货币,我想使用此方法:


% pip show
Name: scipy
Version: 1.0.0rc1
Summary: SciPy: Scientific Library for Python
Home-page: https://www.scipy.org
Author: SciPy Developers
Author-email: scipy-dev@python.org
License: BSD
Location: /usr/local/lib/python2.7/dist-packages
Requires: numpy

答案 7 :(得分:0)

由于我找不到灵活的解决方案,我写了一个简单的函数来获得最佳结果:

function getValueFormattedWithMinimalDecimals($value, $max_decimals = 2, $dec_point = ',', $thousands_sep = '') {
    $bestNumberOfDecimals = -1;
    $decimal = 0;
    while ($decimal <= $max_decimals) {
        $bestNumberOfDecimals = $decimal;
        $valueDecimals = number_format($value, $decimal);
        if (floatval($value) == $valueDecimals) {
            break;
        }
        $decimal++;
    }
    if($bestNumberOfDecimals > 0 && number_format($value, $bestNumberOfDecimals) == number_format($value, 0)) {
        $bestNumberOfDecimals = 0;
    }

    return number_format($value, $bestNumberOfDecimals, $dec_point, $thousands_sep);
}

答案 8 :(得分:0)

我被指控这样做:

 floatval($foo) == intval($foo) ? number_format($foo) : number_format($foo,2);

答案 9 :(得分:0)

由于大多数数量或件不需要小数,该功能仅在需要时显示小数。

str_replace(".00", "", number_format($this->pieces, 2));

答案 10 :(得分:-1)

怎么样?
number_format($value,2) - 0;