Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 964
max Avatar asked Jul 21 '13 11:07

max


People also ask

How do I restrict a float value to only two places after the decimal point in Javascript?

To limit the number of digits up to 2 places after the decimal, the toFixed() method is used. The toFixed() method rounds up the floating-point number up to 2 places after the decimal.

How do you limit a float to two decimal places in C++?

Using the ceil() function to round to 2 decimal places in C++ The ceil() function returns the smallest integer greater than the given integer. It will round up to the nearest integer. We can use this function to round to 2 decimal places in C++.

How many digits can a float represent?

A float has 23 bits of mantissa, and 2^23 is 8,388,608. 23 bits let you store all 6 digit numbers or lower, and most of the 7 digit numbers. This means that floating point numbers have between 6 and 7 digits of precision, regardless of exponent.


1 Answers

<?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
like image 118
user4035 Avatar answered Oct 20 '22 18:10

user4035