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条回答
够拽才男人
2楼-- · 2019-03-09 06:44

You could also use rtrim(), which would remove excess 0s, in the case where you might want to keep one decimal place but not the excess zeros. (For example, 4.50 becomes 4.5.) Also allows you to change the number of decimal places from 2 to any other number.

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)
查看更多
不美不萌又怎样
3楼-- · 2019-03-09 06:46

I add the article Remove useless zero digits from decimals in PHP as a nicer way to clean the value without loose decimal if needed.

查看更多
SAY GOODBYE
4楼-- · 2019-03-09 06:49

As Emil says yours are good. But if you want to remove 0 from e.g. 7.50 too, I've got a suggestion, rtrim():

<?php
    // if $sql_result["col_number"] == 1,455.50
    rtrim(rtrim(number_format($sql_result["col_number"], 2, ".", ""), '0'), '.');
    // will return 1455.5
?>
查看更多
Ridiculous、
5楼-- · 2019-03-09 06:52

I've been accused of doing something like this:

 floatval($foo) == intval($foo) ? number_format($foo) : number_format($foo,2);
查看更多
看我几分像从前
6楼-- · 2019-03-09 06:55

I actually think that your workaround is as good as any. It's simple and clear, and there's really no point talking about performance here, so just go for it.

查看更多
欢心
7楼-- · 2019-03-09 06:57

What about

number_format($value,2) - 0;
查看更多
登录 后发表回答