show 2 digits max after floating point ... only if it is a float number with more than 2 float digits

floating-point, math, php

Solution

<?php
$number = 25;
print round($number, 2);

print "\n";

$number = 25.3;
print round($number, 2);

print "\n";

$number = 25.33;
print round($number, 2);

prints:

25
25.3
25.33

Problem

in my app i do some math and the result can be float or int i want to show the final result with two digit after the decimal point max ... if result is a float number there are two options to do this ``` number_format($final ,2); ``` and ``` sprintf ("%.2f", $final ); ``` but problem is ... if my final result is a int like `25` i end up with ``` 25.00 ``` or if final result is some thing like `12.3` it gives me ``` 12.30 ``` and i dont want that is there any way to format a number to show 2 digits after float point ONLY IF it's a float number with more than 2 digits after decimal point ? or should i do some checking before formatting my number ?

Original source