开发者

Rounding a number in PHP without converting it to the locale's representation

So, apparently PHP's round() outputs the result as a string formatted according to the current locale settings. round( 10000.326, 1 ) might return "1.000,3", which is fine if you intend to display the result right away, but not that great if you plan to work further with it.

php.net discussion hints that there is no way to stop round() from localizing the output. Is there really no "pure" rounding function in the library that would return an int or a float/double so that the result could be used in arithmetical operations开发者_如何学Go, or is creating your own the only option?


round() doesn't output the result as a string formatted according to the current locale settings: it returns a float... and has no localization.

float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )

What you do with the result afterwards is more likely to localize it.

Where did you get the impression that round() returned a localized string?


I'm not too much of an expert, but perhaps number_format() might give you what you need? Based on the comments it doesn't appear to use locale, and I know it rounds.


Assuming rounding integers:

floor($value + .5);

And add precision like this (this is one digit):

$digits = 1;
floor($value * pow(10, $digits) + .5) / pow(10, d$igits);


use sprintf like :

$val = sprintf('%.1f', 1000.326);

gives : 1000.3


It's the automatic conversion to a string for output that probably causes the confusion. There's a more direct question about that. An example was helpful for me:

<?php
setlocale(LC_NUMERIC, 'en_US');
echo 1.234; // 1.234
setlocale(LC_NUMERIC, 'et_EE.UTF-8');
echo 1.234; // 1,234
echo number_format( 1.234, 2, '.', '' ); // 1.23 
?>


The round function returns a float but the format is localized.

echo round(3.14159, 2);
setlocale(LC_ALL, 'fr_FR');
echo round(3.14159, 2);

This is what the original poster meant.

I suggest:

setlocale(LC_NUMERIC, 'en_US'); 

That will set the localization for the decimal separator to English (United States) and will be a period.


float round ( float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]] )

Where are you see string output???


if you want to force it to int you can type cast like this:

$rnum = (int) round( 10000.326, 1 );

not sure if this is what your looking for though.

you can get more info here http://php.net/manual/en/language.types.type-juggling.php

this is what i did to confirm, i am not sure what your trying to achieve exactely

but this might help

$var = (int) "1.000,3";
$var1 = "1.000,3";

if(is_string($var)) print "true";
else print "false";

if(is_int($var)) print "true";
else print "false";

if(is_string($var1)) print "true";
else print "false";

the results are:

  1. false
  2. true
  3. true

please correct me if i am wrong. thanks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜