Search code examples
phplocale

Ignoring localisation conversion within a PHP function


I've built a multi-language site and I have both locales installed on the server. That's all good. However I have a PHP function that calculates the ratio of an image and returns it throughout my site. Only issue is it's returning the ratio with a comma (because of the localisation).

Any way to turn off the conversion for the following function?

function getRatio($width,$height) {
    $ratio = round($height/$width*100,2);
    $format = $height>$width;
    if ($format) {
        echo "data-format='portrait'";
    } else {
        echo "data-format='landscape'";
    }
    echo "style='padding-bottom:$ratio%;'";
}

Then in my templates:

<?php echo getRatio($image->width,$image->height); ?>

Solution

  • I think it's easier to just use number_format(). This is easier to maintain and is consistent for every locale.

    Note that number_format also rounds, so you can remove the round() from your code.

    // 2 decimals, comma for thousands and point for decimals
    $ratio = number_format($height / $width * 100, 2, ".", ",");
    
    // 2 decimals, point for thousands and comma for decimals
    $ratio = number_format($height / $width * 100, 2, ",", ".");
    
    // 10 decimals, no thousands and point for decimals
    $ratio = number_format($height / $width * 100, 10, ".");
    
    // etc etc etc