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 ?>
The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function.
$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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With