PHP number: decimal point visible only if needed

vitto picture vitto · Nov 6, 2010 · Viewed 34.6k times · Source

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

xDiff picture xDiff · Oct 30, 2014

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