How to convert a decimal to an integer in PHP

1 Answer

0 votes
/*
    ============================================================
    Convert a decimal-like value to an integer in PHP.
 
    This program demonstrates:
      • Conversion using round(), which rounds to the nearest integer.
      • Conversion using intval(), which truncates toward zero.
      • Conversion using (int), which also truncates.
      • A helper function that prints all conversion styles.
 
    Notes:
      • PHP does not have a distinct "long" type; integers expand as needed.
      • round() follows standard rounding rules.
      • intval() and (int) remove the fractional part.
    ============================================================
*/
 
/* Converts a decimal to an integer using rounding */
function convert_decimal_to_integer(float $value): int {
    return round($value);
}
 
/* Converts a decimal to an integer using truncation */
function cast_decimal_to_integer(float $value): int {
    return intval($value);   // same as (int)$value
}
 
/* Prints both conversion styles for comparison */
function show_conversions(float $value): void {
    echo "Input decimal: {$value}\n";
 
    $rounded   = convert_decimal_to_integer($value);
    $truncated = cast_decimal_to_integer($value);
 
    echo "Rounded (round): {$rounded}\n";
    echo "Truncated (intval): {$truncated}\n\n";
}
 
/* Main */
show_conversions(12.7);
show_conversions(12.3);
show_conversions(-5.8);
show_conversions(42.0);   // already an integer
 
 
/*
run:
 
Input decimal: 12.7
Rounded (round): 13
Truncated (intval): 12
 
Input decimal: 12.3
Rounded (round): 12
Truncated (intval): 12
 
Input decimal: -5.8
Rounded (round): -6
Truncated (intval): -5
 
Input decimal: 42
Rounded (round): 42
Truncated (intval): 42
 
*/

 



answered Aug 6 by avibootz
edited Aug 6 by avibootz
...