Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?> 
like image 537
vitto Avatar asked Nov 06 '10 13:11

vitto


People also ask

How can I limit float to 2 decimal places in PHP?

The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function.

How can I get value to 2 decimal places in PHP?

$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Show activity on this post. This will give you 2 number after decimal.

How check value is decimal or not in PHP?

The is_numeric() function in the PHP programming language is used to evaluate whether a value is a number or numeric string. Numeric strings contain any number of digits, optional signs such as + or -, an optional decimal, and an optional exponential. Therefore, +234.5e6 is a valid numeric string.


2 Answers

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 
like image 185
xDiff Avatar answered Sep 23 '22 18:09

xDiff


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.

like image 28
Emil H Avatar answered Sep 19 '22 18:09

Emil H