Jump to content

Only display decimals if they're present


davidcriniti

Recommended Posts

Hi guys,

 

I've got a line of code that asks for a column called "distance_completed" to be displayed as part of a string.

 

This column tells users how far people have run in a running race.

 

I set up this field in my database to 11,3 so all distances appear with a decimal at the end, and then 3 digits after the decimal place.

 

How would I alter the code so that the numbers that don't have any information in the places section just appear as integers Eg: 42 instead of 42.000 (for someone who ran exaclty 42km) and those that do have information in the decimal places appear correctly (eg: if a person ran 42km and 195m, it would appear as 42.195).

 

I think this is probably the only line of code that would need modification:

 


echo ($row['time'] != null)?$row["time"]:"dnf at ".$row["distance_completed"]."km.";

Link to comment
https://forums.phpfreaks.com/topic/214577-only-display-decimals-if-theyre-present/
Share on other sites

...but I don't necessarily want to round it off. Eg: If the value was 42.195, I'm happy to keep it that 42.195.

 

I'd only like numbers changed when there is no information on the right-hand-side of the decimal.

 

Eg: If someone ran exactly 20km, I'd like to see 20      ....rather than 20.000

 

Not sure if this is possible or not?

You can just specify the decimal in the rtrim character list, too.

 

rtrim($num, '0.');

 

$num = array(1.0001, 1.00, 3.3345, 4.0, 5.55, 6.7800000000);
foreach( $num as $v ) {
rtrim($v, '0.');
echo $v . '<br>';
}
// RETURNS:
/*
1.0001
1
3.3345
4
5.55
6.78
*/

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.