vitto vitto - 1 month ago 10
PHP Question

PHP number: decimal point visible only if needed

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

Answer

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.