PHP 字符串浮动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/481466/
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-24 22:53:10  来源:igfitidea点击:

PHP String to Float

phpstringcastingfloating-point

提问by Sampson

I am not familiar with PHP at all and had a quick question.

我根本不熟悉 PHP,有一个简短的问题。

I have 2 variables pricePerUnitand InvoicedUnits. Here's the code that is setting these to values:

我有 2 个变量pricePerUnitInvoicedUnits. 这是将这些设置为值的代码:

$InvoicedUnits = ((string) $InvoiceLineItem->InvoicedUnits);
$pricePerUnit = ((string) $InvoiceLineItem->PricePerUnit);

If I output this, I get the correct values. Lets say 5000invoiced units and 1.00for price.

如果我输出这个,我会得到正确的值。让我们说5000发票单位和1.00价格。

Now, I need to show the total amount spent. When I multiply these two together it doesn't work (as expected, these are strings).

现在,我需要显示花费的总金额。当我将这两个相乘时它不起作用(正如预期的那样,这些是字符串)。

But I have no clue how to parse/cast/convert variables in PHP.

但我不知道如何在 PHP 中解析/转换/转换变量。

What should I do?

我该怎么办?

回答by Sampson

$rootbeer = (float) $InvoicedUnits;

Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.

应该为你做。查看类型杂耍。您还应该阅读String 到 Numbers 的转换

回答by earino

You want the non-locale-aware floatvalfunction:

您需要非语言环境感知floatval功能

float floatval ( mixed $var ) - Gets the float value of a string.

float floatval ( mixed $var ) - 获取字符串的浮点值。

Example:

例子:

$string = '122.34343The';
$float  = floatval($string);
echo $float; // 122.34343

回答by HADI

Well, if user write 1,00,000 then floatvar will show error. So -

好吧,如果用户写入 1,00,000,那么 floatvar 将显示错误。所以 -

floatval(preg_replace("/[^-0-9\.]/","",$input));

This is much more reliable.

这要可靠得多。

Usage :

用法 :

$input = '1,03,24,23,434,500.6798633 this';
echo floatval(preg_replace("/[^-0-9\.]/","",$input));

回答by Tobias P.

Dealing with markup in floats is a non trivial task. In the English/American notation you format one thousand plus 46*10-2:

处理浮动中的标记是一项重要的任务。在英/美符号中,您格式化一千加46*10-2

1,000.46

But in Germany you would change comma and point:

但在德国,你会改变逗号和点:

1.000,46


This makes it really hard guessing the right number in multi-language applications.
I strongly suggest using Zend_Measureof the Zend Framework for this task. This component will parse the string to a float by the users language.


这使得在多语言应用程序中猜测正确的数字非常困难。
我强烈建议使用Zend_MeasureZend Framework 来完成这项任务。该组件将通过用户语言将字符串解析为浮点数。

回答by Hafenkranich

Use this function to cast a float value from any kind of text style:

使用此函数从任何类型的文本样式转换浮点值:

function parseFloat($value) {
    return floatval(preg_replace('#^([-]*[0-9\.,\' ]+?)((\.|,){1}([0-9-]{1,3}))*$#e', "str_replace(array('.', ',', \"'\", ' '), '', '\1') . '.\4'", $value));
}

This solution is not dependant on any locale settings. Thus for user input users can type float values in any way they like. This is really helpful e.g. when you have a project wich is in english only but people all over the world are using it and might not have in mind that the project wants a dot instead of a comma for float values. You could throw javascript in the mix and fetch the browsers default settings but still many people set these values to english but still typing 1,25 instead of 1.25 (especially but not limited to the translation industry, research and IT)

此解决方案不依赖于任何区域设置。因此,对于用户输入,用户可以以他们喜欢的任何方式键入浮点值。这真的很有帮助,例如,当您有一个仅使用英语的项目但世界各地的人们都在使用它时,并且可能不知道该项目需要一个点而不是逗号来表示浮点值。您可以混合使用 javascript 并获取浏览器的默认设置,但仍然有很多人将这些值设置为英语,但仍然输入 1,25 而不是 1.25(尤其是但不限于翻译行业、研究和 IT)

回答by Morris Buel

I was running in to a problem with the standard way to do this:

我遇到了执行此操作的标准方法的问题:

$string = "one";

$float = (float)$string;

echo $float; : ( Prints 0 )

If there isn't a valid number, the parser shouldn't return a number, it should throw an error. (This is a condition I'm trying to catch in my code, YMMV)

如果没有有效的数字,解析器不应该返回一个数字,它应该抛出一个错误。(这是我试图在我的代码中捕获的条件,YMMV)

To fix this I have done the following:

为了解决这个问题,我做了以下工作:

$string = "one";

$float = is_numeric($string) ? (float)$string : null;

echo $float; : ( Prints nothing )

Then before further processing the conversion, I can check and return an error if there wasn't a valid parse of the string.

然后在进一步处理转换之前,如果没有有效的字符串解析,我可以检查并返回错误。

回答by Jannie Theunissen

If you need to handle values that cannot be converted separately, you can use this method:

如果需要处理无法单独转换的值,可以使用这种方法:

try {
    $valueToUse = trim($stringThatMightBeNumeric) + 0;
} catch (\Throwable $th) {
    // bail here if you need to
}