什么是针对PHP gettext的setlocale的适当结构,并避免类型定义错误

THE ISSUE

I start to implement gettext for the i18n in the PHP related files. Even though there are many tutorials on the web, I have difficulties finding a clear answer where to position the setlocale in the script ?. Everyone seems to position it at the beginning of the script.

THE EXAMPLE

gettext works pretty fine with the following PHP functions, but I have issues with other PHP functions (see comments below):

$category = LC_ALL;
$locale = "fr_FR";
$domain = "messages";
$lat = 43.848977; // float with a point separator

setlocale( $category, "$locale" );
putenv( "$category=$locale" );
bindtextdomain( $domain, "./Locale" );
bind_textdomain_codeset( $domain, 'UTF-8' );

echo gettext("sample text"); // works OK

// The issue starts here
$center_lat = filter_var( $lat, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ); 
// The float $latitude is interpreted as string due to comma in French,
// filter_var do interpret as a float anymore and $center_lat gives something like 43848977 instead of 43,848977

THE SOLUTION I THOUGHT

I Though that I must do something like this (almost) each time I call gettext:

$userLocale = setlocale( $category, 0 ); // current setting is returned
echo gettext( "sample text" );
setlocale( $category, $userLocale );

// SCRIPT RESUME

$userLocale = setlocale( $category, 0 ); // current setting is returned
echo gettext( "other text" );
setlocale( $category, $userLocale );

I did not find a full file example nor clear answer in the official manual of gettext

I TRIED

I tried Type Casting without success:

$center_lat = filter_var( (float) $lat, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION ); 

THE QUESTION

Is my solution the way to go to avoid unexpected errors (whether it is Type Casting or any other) ?

filter_var() is usually used to check your web form input, where the input values are given in string I think. In what situation will it need to check float by filter_var()?

Anyway, to check locale formatted number, you could use php_intl extension to convert the French number string to regular one, then filter_var() should work.

if (!class_exists('NumberFormatter')) {
    exit ('You need to install php_intl extension.');
}

$category = LC_ALL;
$locale = "fr_FR";
$domain = "messages";
$lat = '43,848977';

setlocale( $category, "$locale" );
putenv( "$category=$locale" );
bindtextdomain( $domain, "./Locale" );
bind_textdomain_codeset( $domain, 'UTF-8' );

$localeFormatter = new \NumberFormatter($locale, \NumberFormatter::DECIMAL); 
$center_lat = filter_var(
    $localeFormatter->parse($lat),
    FILTER_SANITIZE_NUMBER_FLOAT,
    FILTER_FLAG_ALLOW_FRACTION
);
echo $center_lat . PHP_EOL;