cil*_*ili 34 php floating-point parsing currency
有没有办法得到像这样的字符串的浮点值:75,25 €除了parsefloat(str_replace(',', '.', $var))?
我希望这依赖于当前的网站语言,有时逗号可以用点替换.
mcu*_*ros 46
这是一个更复杂/更慢的解决方案,但适用于所有语言环境.因为@ rlenom的解决方案仅使用点作为小数分隔符,并且某些语言环境(如西班牙语)使用逗号作为小数分隔符.
<?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);
}
Run Code Online (Sandbox Code Playgroud)
测试:
['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]
Run Code Online (Sandbox Code Playgroud)
注意事项:如果小数部分超过两位数,则会失败.
这是来自此库的实现:https: //github.com/mcuadros/currency-detector
Gor*_*don 43
您可以使用
手册示例:
$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
var_dump($formatter->parseCurrency("75,25 €", $curr));
Run Code Online (Sandbox Code Playgroud)
得到: float(75.25)
rle*_*mon 42
使用ereg_replace
$string = "$100,000";
$int = ereg_replace("[^0-9]", "", $string);
echo $int;
Run Code Online (Sandbox Code Playgroud)
输出
百万
function toInt($str)
{
return (int)preg_replace("/\..+$/i", "", preg_replace("/[^0-9\.]/i", "", $str));
}
Run Code Online (Sandbox Code Playgroud)
更新
<?php
$string = array("$1,000,000.00","$1 000 000.00","1,000 000.00","$123","$123 456 789","0.15¢");
foreach($string as $s) {
echo $s . " = " . toInt($s) . "\n";
}
function toInt($str)
{
return preg_replace("/([^0-9\\.])/i", "", $str);
}
?>
Run Code Online (Sandbox Code Playgroud)
输出
$1,000,000.00 = 1000000.00
$1 000 000.00 = 1000000.00
1,000 000.00 = 1000000.00
$123 = 123
$123 456 789 = 123456789
0.15¢ = 0.15
Run Code Online (Sandbox Code Playgroud)
如果你把它作为一个整数
<?php
$string = array("$1,000,000.00","$1 000 000.00","1,000 000.00","$123","$123 456 789","0.15¢");
foreach($string as $s) {
echo $s . " = " . _toInt($s) . "\n";
}
function _toInt($str)
{
return (int)preg_replace("/([^0-9\\.])/i", "", $str);
}
?>
Run Code Online (Sandbox Code Playgroud)
输出
$1,000,000.00 = 1000000
$1 000 000.00 = 1000000
1,000 000.00 = 1000000
$123 = 123
$123 456 789 = 123456789
0.15¢ = 0
Run Code Online (Sandbox Code Playgroud)
所以你有它.单行,一个替换.你很高兴.
您需要从字符串中删除货币符号.PHP intval在它找到的第一个非数字字符处停止.
$int = intval(preg_replace('/[^\d\.]/', '', '$100')); // 100
Run Code Online (Sandbox Code Playgroud)
虽然如果你有类似的价值$100.25,你可能想要使用floatval.
$float = floatval(preg_replace('/[^\d\.]/', '', '$100.25')); // 100.25
Run Code Online (Sandbox Code Playgroud)