在 PHP 中解析时取消格式化钱

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5139793/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:54:32  来源:igfitidea点击:

Unformat money when parsing in PHP

phpparsingfloating-pointcurrency

提问by cili

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

有没有办法像这样获取字符串的浮点值:75,25 ,而不是parsefloat(str_replace(',', '.', $var))

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

我希望这取决于当前的站点语言,有时逗号可以用点代替。

回答by mcuadros

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.

这是一个更复杂/缓慢的解决方案,但适用于所有语言环境。@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);
}

Tests:

测试:

['1,10 USD', 1.10],
['1 000 000.00', 1000000.0],
[' 000 000.21', 1000000.21],
['£1.10', 1.10],
['3 456 789', 123456789.0],
['3,456,789.12', 123456789.12],
['3 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

这是这个库的一个实现:https: //github.com/mcuadros/currency-detector

回答by rlemon

use ereg_replace

使用 ereg_replace

$string = "0,000";
$int = ereg_replace("[^0-9]", "", $string); 
echo $int;

outputs

产出

1000000

1000000

function toInt($str)
{
    return (int)preg_replace("/\..+$/i", "", preg_replace("/[^0-9\.]/i", "", $str));
}


Update

更新



<?php
$string = array(",000,000.00"," 000 000.00","1,000 000.00","3","3 456 789","0.15¢");
foreach($string as $s) {
    echo $s . " = " . toInt($s) . "\n"; 
}
function toInt($str)
{
    return preg_replace("/([^0-9\.])/i", "", $str);
}
?>

Outputs

输出

,000,000.00 = 1000000.00
 000 000.00 = 1000000.00
1,000 000.00 = 1000000.00
3 = 123
3 456 789 = 123456789
0.15¢ = 0.15

and if you cast it as an integer

如果你把它作为一个整数

<?php
$string = array(",000,000.00"," 000 000.00","1,000 000.00","3","3 456 789","0.15¢");
foreach($string as $s) {
    echo $s . " = " . _toInt($s) . "\n";    
}
function _toInt($str)
{
    return (int)preg_replace("/([^0-9\.])/i", "", $str);
}
?>

outputs

产出

,000,000.00 = 1000000
 000 000.00 = 1000000
1,000 000.00 = 1000000
3 = 123
3 456 789 = 123456789
0.15¢ = 0

So there you have it. single line, one replace. you're good to go.

所以你有它。单行,一个替换。你可以走了。

回答by Gordon

You can use

您可以使用

Example from Manual:

手册中的示例:

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

gives: float(75.25)

给出: float(75.25)

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

请注意,默认情况下不启用intl 扩展。请参阅安装说明

回答by Rocket Hazmat

You're gonna need to remove the currency symbol from the string. PHP's intvalstops at the 1st non-numeric character it finds.

您需要从字符串中删除货币符号。PHPintval在它找到的第一个非数字字符处停止。

$int = intval(preg_replace('/[^\d\.]/', '', '0')); // 100

Though if you have a value like $100.25, you might wanna use floatvalinstead.

虽然如果你有一个像 的值$100.25,你可能想floatval改用。

$float = floatval(preg_replace('/[^\d\.]/', '', '0.25')); // 100.25

回答by sdleihssirhc

PHP has intval(here are the docs), which is (as far as I can tell) exactly the same as JavaScript's parseInt.

PHP 有intval这里是文档),它(据我所知)与 JavaScript 的parseInt.

However, for what's worth, I don't think either function will help you with what you're trying to do. Because the first character is non-numeric, both freak out (PHP will give you 0, JS will give you NaN). So in either language, you're going to have to do some string/regex parsing.

但是,就其价值而言,我认为这两个功能都不会帮助您完成您正在尝试做的事情。因为第一个字符是非数字的,所以两个都吓坏了(PHP 会给你 0,JS 会给你NaN)。因此,无论哪种语言,您都必须进行一些字符串/正则表达式解析。

回答by Naftali aka Neal

Casting is your friend:

铸造是你的朋友:

$int = (int) $string;


Updatebased on op:

基于 op 的更新

Try something like this:

尝试这样的事情:

<?php

function extract_numbers($string)
{
    return preg_replace("/[^0-9]/", '', $string);
}

echo extract_numbers('0');

?>

Demo: http://codepad.org/QyrfS7WE

演示:http: //codepad.org/QyrfS7WE

回答by Edson Medina

I had a similar problem where I didn't receive the currency symbol, just the strings (ie: 1,234,567.89 or 1.234.567,89).

我有一个类似的问题,我没有收到货币符号,只有字符串(即:1,234,567.89 或 1.234.567,89)。

This helped me normalize both cases into floats:

这帮助我将这两种情况规范化为浮点数:

$val = str_replace(",", ".", $formatted);
$val = preg_replace("/[\,\.](\d{3})/", "", $val);

But Gordon's answer is much cleaner.

但戈登的回答要简洁得多。

回答by user2840024

I'm an newbie, so there's probably an obvious (to others, not me) downside to the approach below, but thought I would share it anyway. I'd be interested to know whether it's faster or slower than using preg_replace, but didn't do any speed testing.

我是一个新手,所以下面的方法可能有一个明显的(对其他人,而不是我)缺点,但我想无论如何我都会分享它。我很想知道它比使用 preg_replace 快还是慢,但没有做任何速度测试。

$badChars = array("$", ",", "(", ")");
$dirtyString = "(,895.23)";
$cleanString = str_ireplace($badChars, "", $dirtyString);
echo "$dirtyString becomes $cleanString<p>";

$dirtyString can be an array, so:

$dirtyString 可以是一个数组,所以:

$badChars = array("$", ",", "(", ")");
$dirtyStrings = array("(,895.23)", "1,067.04", "83.22", "34.48");
$cleanStrings = str_ireplace($badChars, "", $dirtyStrings);

echo var_dump($cleanStrings);