PHP number: decimal point visible only if needed PHP number: decimal point visible only if needed php php

PHP number: decimal point visible only if needed


floatval or simply casting to float

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


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.


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