How do I echo a variable that is double, but only show decimals if needed?

I have several double fields in my database and when repeating fields in my php I get .00 at the end of the values.

How do I display .00 , but display, is there a value?

+4
source share
5 answers

You can use str_replace to remove ".00" from the values.

 $value = 10.00; echo str_replace('.00', '', $value); // 10 $value = 10.52; echo str_replace('.00', '', $value); // 10.52 
+1
source
 echo (int)$double; 

will just delete decimals. if you just want to hide the decimal numbers "zero" (10.00 → 10), but leave non-zero decimal numbers (10.1 → 10.1), then you will need to do some processing:

 echo preg_replace('/\.0+$/', '', $double); 

which would process any number of zeros after the decimal place, but leave non-zero values.

+1
source
 if (fmod($number, 1) == 0) { $number = intval($number); } else { $number = round($number, 2); } 

Or just use round() [@ ideone.com ]:

 var_dump(round($number = 5.00, 2)); // 5 var_dump(round($number = 5.01, 2)); // 5.01 
+1
source

For an arbitrary number 0 at the end of the number:

 $number = rtrim($number,".0"); 

Examples:

 Input : 1.00 Result: 1 Input : 1.25 Result: 1.25 Input : 1.40 Result: 1.4 Input : 1.234910120000 Result: 1.23491012 
+1
source
 select number,if(number % 1 = 0,cast(number as unsigned),number) from table 
0
source

All Articles