Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse formatted Money String into Number [duplicate]

Is there a way to get the float value of a string like this: 75,25 €, other than parsefloat(str_replace(',', '.', $var))?

I want this to be dependent on the current site language, and sometimes the comma could be replaced by dot.

like image 844
cili Avatar asked Feb 28 '11 08:02

cili


2 Answers

You can use

  • NumberFormatter::parseCurrency - Parse a currency number

Example from Manual:

$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
var_dump($formatter->parseCurrency("75,25 €", $curr));

gives: float(75.25)

Note that the intl extension is not enabled by default. Please refer to the Installation Instructions.

like image 167
Gordon Avatar answered Sep 28 '22 08:09

Gordon


This is a bit more complex/ slow solution, but works with all locales. @rlenom's solution work only with dots as decimal separator, and some locales, like Spanish, use the comma as decimal separator.

<?php

public function getAmount($money)
{
    $cleanString = preg_replace('/([^0-9\.,])/i', '', $money);
    $onlyNumbersString = preg_replace('/([^0-9])/i', '', $money);

    $separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;

    $stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
    $removedThousandSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '',  $stringWithCommaOrDot);

    return (float) str_replace(',', '.', $removedThousandSeparator);
}

Tests:

['1,10 USD', 1.10],
['1 000 000.00', 1000000.0],
['$1 000 000.21', 1000000.21],
['£1.10', 1.10],
['$123 456 789', 123456789.0],
['$123,456,789.12', 123456789.12],
['$123 456 789,12', 123456789.12],
['1.10', 1.1],
[',,,,.10', .1],
['1.000', 1000.0],
['1,000', 1000.0]

Caveats: Fails if the decimal part have more than two digits.

This is an implementation from this library: https://github.com/mcuadros/currency-detector

like image 28
mcuadros Avatar answered Sep 28 '22 10:09

mcuadros