setlocale to fr-FR in PHP and number formatting

2019-02-18 11:52发布

I am trying to create a French version of one of my sites. I have set setlocale(LC_ALL, 'fr_FR'); at the top of my page, and using strftime I am displaying dates correctly in the French style.

However I am having some problems with a number. Part of the page uses data I am getting from a Web Service. I am assigning a returned value to a var like this:

$overallRating = $returnArray['Overall'];

I am then using the following code later to format it to 1 decimal place

number_format($overallRating,1)

In the English version the overallRating value might be 7.5 and returns a value such as 7.5 (the reason for running it through the number_format is if it returns 7 I want it to display 7.0)

However in the French version if I print out the raw $overallRating value I get 7,5 which looks like it has translated it into french. This would be fine but if I run it through number_format I get the error:

Notice: A non well formed numeric value encountered in /sites/index.php  on line 250

Line 250 is the number_format line

I presume the translation to 7,5 is messing it up, but not sure how to solve this...

Using PHP 5.3 in case there is anything new that helps me

3条回答
ら.Afraid
2楼-- · 2019-02-18 12:20

is this what you are asking ?

<?php
    $overallRating = number_format($number, 1, '.', '');
?>

Later Edit:

<?php
setlocale(LC_ALL, 'fr_FR');
$number = '7';
echo $overallRating = number_format($number, 1, '.', '');
?>
查看更多
淡お忘
3楼-- · 2019-02-18 12:21

So eventually found the answer after a lot of research.

PHP only really works with standard US decimal seperators and can't cope with the french , seperator.

The answer, although not perfect is to reset numeric values to use US while allowing dates etc to be formatted in French. Placing this line:

 setlocale(LC_NUMERIC, 'C');

Under

 setlocale(LC_ALL, 'fr_FR'); 

has done the trick

查看更多
闹够了就滚
4楼-- · 2019-02-18 12:27

I wanted to take a French-edited string like "54,33" and save it back to the db as en_US number because, as has been pointed out, PHP really only likes numbers in the en_US format. I didn't see any built-in PHP conversion functions so built this to do the job. Removes the thousands separator and replaces the decimal separator with "." and it's designed to work with any setup.

//Currency Conversion Back to US for DB Storage or PHP number formatting
function number_convert_us($num) {
    $locale_settings = localeconv();
    $num = str_replace($locale_settings['mon_thousands_sep'], "", trim($num));
    $num = str_replace($locale_settings['mon_decimal_point'], ".", $num);
    return number_format((double)$num, 2, '.', '');
}

I'll build a similar thing for JavaScript. Found this library for display: http://software.dzhuvinov.com/jsworld-currency-formatting.html

查看更多
登录 后发表回答