php - Check if variable with a number stored as contains a decimal point -
i'm checking if custom field has decimal, , adding ".0" if doesn't.
for reason, keep getting incorrect outputs: adds decimal either way.
function containsdecimal( $value ) { if ( strpos( $value, "." ) !== false ) { echo "$value.0"; } else { echo "$value"; }}
and call:
<?php containsdecimal(the_field('carbs-g')); ?> <?php containsdecimal(the_field('fiber-g')); ?>
with carbs-g = 1.2 , fiber-g = 0...
this returns: 1.2.0 , 0.0
when use call correct results:
<?php containsdecimal(1.2); ?> <?php containsdecimal(0); ?>
this returns: 1.2 , 0.0
your logic backwards :-)
you adding ".0" when number has decimal (the strpos result isn't false).
should adding when strpos result is false (the number doesn't have decimal).
function containsdecimal( $value ) { if ( strpos( $value, "." ) === false ) { echo "$value.0"; } else { echo "$value"; } }
Comments
Post a Comment