2

I get an int in U.S format.

$UsInt = "67,450";

I need to convert it in European format.

$EuInt = "67450";

I can not use str_replace() to replace the virgule. Do not use str_replace() is a mandatory deposit.

i can't use number_format(), because i can't pass a comma separated number to this function

Would exist a PHP function to do this? Or someone has already had the problem and was able to get out?

mortiped
  • 869
  • 1
  • 6
  • 28
  • If `str_replace` is banned, how about `preg_replace`? – Passerby Nov 06 '13 at 10:12
  • 1
    This could help, it is about money but it's the same... http://stackoverflow.com/questions/7407946/parse-formatted-money-string-into-number – Salketer Nov 06 '13 at 10:14
  • the client to put these requirements do not use functions such as str_replace () or preg_replace (). because int recovered is written manually, if you use 'str_replace' and if the user made a mistake there will be a problem. if you just format U.S. to EU there is not the risk of error. – mortiped Nov 06 '13 at 10:33
  • well, you want to put some error checking into your code anyway. there is no magic fool-proof solution. – Gordon Nov 06 '13 at 10:46
  • I can't do that, because the int I take is already write and i can't say at the user "it's wrong". – mortiped Nov 06 '13 at 10:52

3 Answers3

3

You can use the PHP function number_format() :

  $EuInt = number_format($UsInt)

For more information you can head to the PHP manual

Pranav 웃
  • 8,469
  • 6
  • 38
  • 48
Michel Sahli
  • 1,059
  • 10
  • 14
  • 2
    You can't pass a comma separated number to this function. – Chris Nov 06 '13 at 10:16
  • 1
    I don't think this works: http://3v4l.org/jSLGK Because according to the document you linked, `number_format` expects the first parameter a float, not a string. – Passerby Nov 06 '13 at 10:20
3

To "unformat" the string, you can use

Example with your formatted strings:

$fmt = new NumberFormatter( 'en_US', NumberFormatter::DECIMAL );
$int = $fmt->parse("67,450");

This will give you the raw integer, e.g. 67450 in $int.

Then you can either use number_format or use

Example from Manual:

$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo $fmt->format($int);

which would then give 67.450 (with a dot as the thousand separator).

Note that the formatting depends on the locale. And while the region part of a locale might point to Europe, it's not a valid locale on it's own afaik. The British use a comma as the thousand separator (67,450), while the French use a space (67 450) and the Germans use a dot (67.450).

For more information on parsing and formatting numbers, see:

Gordon
  • 312,688
  • 75
  • 539
  • 559
2

Edit: @Gordon♦s solution should be the best.

Not the fastest way, but it should work:

$usInt = '67,450';
$explode = explode(',', $usInt);
$euInt = '';

foreach ($explode as $val) {
    $euInt .= $val;
}

echo $euInt;
Chris
  • 4,255
  • 7
  • 42
  • 83