PHP number: decimal point visible only if needed

2019-03-09 06:26发布

I'd like to know if exists some function to automatically format a number by it's decimal, so if I have:

<?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?
?>

so my answer is if does exist some way to remove the decimals if I have DECIMAL data forma in my DB only when it's round?

Or shoud I do something like that?

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

11条回答
Ridiculous、
2楼-- · 2019-03-09 06:58

Warren.S answer helped me out. I didn't need the number_format function, so I just did this

$value=$value-0;

But in the OP's case, he needs number_format to remove the commas. So this would work for him

$value=number_format ($sql_result["col_number"], 2, ".", "")-0;
查看更多
时光不老,我们不散
3楼-- · 2019-03-09 07:00

floatval or simply casting to float

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
查看更多
叼着烟拽天下
4楼-- · 2019-03-09 07:02

Actually I think the cleanest way I can think of to do this for someone that just did a search looking for this sort of thing is to do this:

( number_format ($sql_result["col_number"], 2) * 100 ) / 100;
查看更多
姐就是有狂的资本
5楼-- · 2019-03-09 07:06

Since I could not find a flexible solution I wrote a simple function to get the best result:

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);
}
查看更多
萌系小妹纸
6楼-- · 2019-03-09 07:10

If you are targeting US currency I like to use this method:

function moneyform($number, $symbol = true) {
    return str_replace(".00", "", money_format(($symbol? '%.2n' : "%!n"), $number));
}

moneyform(1300999);
-->$1,300,999

moneyform(2500.99);
-->$2,500.99

moneyform(2500.99, false);
-->2,500.99
查看更多
登录 后发表回答