php str to float

PHP String to Float

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

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

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.

8 Answers 8

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

php str to float. Смотреть фото php str to float. Смотреть картинку php str to float. Картинка про php str to float. Фото php str to float

This is much more reliable.

php str to float. Смотреть фото php str to float. Смотреть картинку php str to float. Картинка про php str to float. Фото php str to float

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

But in Germany you would change comma and point:

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

php str to float. Смотреть фото php str to float. Смотреть картинку php str to float. Картинка про php str to float. Фото php str to float

you can follow this link to know more about How to convert a string/number into number/float/decimal in PHP. HERE IS WHAT THIS LINK SAYS.

Method 1: Using number_format() Function. The number_format() function is used to convert a string into a number. It returns the formatted number on success otherwise it gives E_WARNING on failure.

Method 2: Using type casting: Typecasting can directly convert a string into a float, double, or integer primitive type. This is the best way to convert a string into a number without any function.

Method 3: Using intval() and floatval() Function. The intval() and floatval() functions can also be used to convert the string into its corresponding integer and float values respectively.

Method 4: By adding 0 or by performing mathematical operations. The string number can also be converted into an integer or float by adding 0 with the string. In PHP, performing mathematical operations, the string is converted to an integer or float implicitly.

Источник

floatval

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

floatval — Возвращает значение переменной в виде числа с плавающей точкой

Описание

Возвращает значение переменной value в виде числа с плавающей точкой ( float ).

Список параметров

Может быть любого скалярного типа. floatval() нельзя использовать с объектами, в этом случае возникнет ошибка уровня E_NOTICE и функция вернёт 1.

Возвращаемые значения

Значение заданной переменной в виде числа с плавающей точкой. Пустые массивы в качестве аргумента возвращают 0, непустые массивы возвращают 1.

Строки чаще всего возвращают 0, тем не менее результат зависит от самых левых символов строки. Применяются правила приведения к float.

Примеры

Пример #1 Пример использования floatval()

Пример #2 Пример использования floatval() с нечисловыми крайними левыми символами

Смотрите также

User Contributed Notes 23 notes

This function takes the last comma or dot (if any) to make a clean float, ignoring thousand separator, currency or any other letter :

$num = ‘1.999,369€’;
var_dump(tofloat($num)); // float(1999.369)
$otherNum = ‘126,564,789.33 m²’;
var_dump(tofloat($otherNum)); // float(126564789.33)

you can also use typecasting instead of functions:

There is much easier way to deal with formatted numbers:

To view the very large and very small numbers (eg from a database DECIMAL), without displaying scientific notation, or leading zeros.

FR : Pour afficher les très grand et très petits nombres (ex. depuis une base de données DECIMAL), sans afficher la notation scientifique, ni les zéros non significatifs.

Easier-to-grasp-function for the ‘,’ problem.

echo Getfloat ( «$ 19.332,35-» ); // will print: 19332.35
?>

locale aware floatval:

The last getFloat() function is not completely correct.

1.000.000 and 1,000,000 and its negative variants are not correctly parsed. For the sake of comparing and to make myself clear I use the name parseFloat in stead of getFloat for the new function:

$pregResultA = array();
$pregResultB = array();

Источник

Точность чисел с плавающей точкой

Числа с плавающей точкой имеют ограниченную точность. Хотя это зависит от операционной системы, в PHP обычно используется формат двойной точности IEEE 754, дающий максимальную относительную ошибку округления порядка 1.11e-16. Неэлементарные арифметические операции могут давать большие ошибки, и, разумеется, необходимо принимать во внимание распространение ошибок при совместном использовании нескольких операций.

Так что никогда не доверяйте точности чисел с плавающей точкой до последней цифры и не проверяйте напрямую их равенство. Если вам действительно необходима высокая точность, используйте математические функции произвольной точности и gmp-функции.

«Простое» объяснение можно найти в » руководстве по числам с плавающей точкой, которое также называется «Why don’t my numbers add up?» («Почему мои числа не складываются?»)

Преобразование в число с плавающей точкой

Из строк

Если строка содержащая число или ведущая числовая, тогда она будет преобразована в соответствующее целочисленное значение, в противном случае она преобразуется в ноль ( 0 ).

Из других типов

Для значений других типов преобразование выполняется путём преобразования значения сначала в целое число ( int ), а затем в число с плавающей точкой ( float ). Смотрите Преобразование в целое число для получения дополнительной информации.

Поскольку определённые типы имеют неопределённое поведение при преобразовании в целое число ( int ), то же самое происходит и при преобразовании в число с плавающей точкой ( float ).

Сравнение чисел с плавающей точкой

Как указано выше, проверять числа с плавающей точкой на равенство проблематично из-за их внутреннего представления. Тем не менее, существуют способы для их сравнения, которые работают несмотря на все эти ограничения.

Для сравнения чисел с плавающей точкой используется верхняя граница относительной ошибки при округлении. Эта величина называется машинной эпсилон или единицей округления (unit roundoff) и представляет собой самую маленькую допустимую разницу при расчётах.

= 1.23456789 ;
$b = 1.23456780 ;
$epsilon = 0.00001 ;

User Contributed Notes 36 notes

PHP thinks that 1.6 (coming from a difference) is not equal to 1.6. To make it work, use round()

var_dump(round($x, 2) == round($y, 2)); // this is true

While the author probably knows what they are talking about, this loss of precision has nothing to do with decimal notation, it has to do with representation as a floating-point binary in a finite register, such as while 0.8 terminates in decimal, it is the repeating 0.110011001100. in binary, which is truncated. 0.1 and 0.7 are also non-terminating in binary, so they are also truncated, and the sum of these truncated numbers does not add up to the truncated binary representation of 0.8 (which is why (floor)(0.8*10) yields a different, more intuitive, result). However, since 2 is a factor of 10, any number that terminates in binary also terminates in decimal.

I’d like to point out a «feature» of PHP’s floating point support that isn’t made clear anywhere here, and was driving me insane.

Will fail in some cases due to hidden precision (standard C problem, that PHP docs make no mention of, so I assumed they had gotten rid of it). I should point out that I originally thought this was an issue with the floats being stored as strings, so I forced them to be floats and they still didn’t get evaluated properly (probably 2 different problems there).

To fix, I had to do this horrible kludge (the equivelant of anyway):

if (round($a,3)>=round($b,3)) echo «blah!»;

THIS works. Obviously even though var_dump says the variables are identical, and they SHOULD BE identical (started at 0.01 and added 0.001 repeatedly), they’re not. There’s some hidden precision there that was making me tear my hair out. Perhaps this should be added to the documentation?

Concider the following:

19.6*100 cannot be compaired to anything without manually
casting it as something else first.

Rule of thumb, if it has a decimal point, use the BCMath functions.

The ‘floating point precision’ box in practice means:

This returns 0.1 and is the workaround we use.

So, that’s all lovely then.

In some cases you may want to get the maximum value for a float without getting «INF».

var_dump(1.8e308); will usually show: float(INF)

I wrote a tiny function that will iterate in order to find the biggest non-infinite float value. It comes with a configurable multiplicator and affine values so you can share more CPU to get a more accurate estimate.

I haven’t seen better values with more affine, but well, the possibility is here so if you really thing it’s worth the cpu time, just try to affine more.

Best results seems to be with mul=2/affine=1. You can play with the values and see what you get. The good thing is this method will work on any system.

Beware of NaN and strings in PHP.
In other languages (and specifically in Javascript) math operations with non-numerical strings will result in NaN, while in PHP the string is silently converted to 0.

is_nan(‘hello, string’); // false

gives the impression that the string is a valid number.

Be careful when using float values in strings that are used as code later, for example when generating JavaScript code or SQL statements. The float is actually formatted according to the browser’s locale setting, which means that «0.23» will result in «0,23». Imagine something like this:

This would result in a different result for users with some locales. On most systems, this would print:

but when for example a user from Germany arrives, it would be different:

which is obviously a different call to the function. JavaScript won’t state an error, additional arguments are discarded without notice, but the function doBar(a) would get 0 as parameter. Similar problems could arise anywhere else (SQL, any string used as code somewhere else). The problem persists, if you use the «.» operator instead of evaluating the variable in the string.

So if you REALLY need to be sure to have the string correctly formatted, use number_format() to do it!

To simply convert 32 bits float from hex to float:

To compare two numbers use:

In the gettype() manual, it says «(for historical reasons «double» is returned in case of a float, and not simply «float») «.

However, I think that internally PHP sometimes uses the C double definition (i.e. a double is twice the size of a float/real). See the example below:

(The strrev_x-bin2hex combination is just to give printable characters.)

Given that PHP treats doubles and floats identically, I’d expected the same string as output, however, the output is:

double pack
string(16) «3ff999999999999a» //Here you see that there is a minute difference.
string(16) «3ff9999999999998»
float pack
string(8) «3fcccccd» //. which doesn’t exist here
string(8) «3fcccccd»

Convert a hex string into a 32-bit IEEE 754 float number. This function is 2 times faster then the below hex to 32bit function. This function only changes datatypes (string to int) once. Also, this function is a port from the hex to 64bit function from below.

But, please don’t use your own «functions» to «convert» from float to binary and vice versa. Looping performance in PHP is horrible. Using pack/unpack you use processor’s encoding, which is always correct. In C++ you can access the same 32/64 data as either float/double or 32/64 bit integer. No «conversions».

PHP switches from the standard decimal notation to exponential notation for certain «special» floats. You can see a partial list of such «special» values with this:

I have to be honest: this is one of the strangest things I have seen in any language in over 20 years of coding, and it is a colossal pain to work around.

Just another note about the locales. Consider the following code:

convert 32bit HEX values into IEEE 754 floating point
= «C45F82ED» ;

I’ve just come across this issue with floats when writing a function for pricing. When converting from string to a float, with 2 digits of precision, the issue with comparing floats can pop up and give inconsistent results due to the conversion process.

An easier way rather than relying on the mentioned epsilon method is to use number_format (at least for me as I’ll remember it!).

Example function that can return an unexpected result:

if((float)$a == (float)$b) <
echo true;
> else <
echo false;
>

echo’s false in this example.

Using number format here to trim down the precision (2 point precision being mostly used for currencies etc, although higher precisions should be correctly catered for by number_format), will return an expected result:

if(number_format((float)$a, 2) == number_format((float)$b, 2)) <
echo true;
> else <
echo false;
>

Correctly echo’s true.

My BIN to FLOAT (IEEE754), the first one doesn’t work for me:

As «m dot lebkowski+php at gmail dot com» (http://www.php.net/language.types.float#81416) noted 9 comments below :

When PHP converts a float to a string, the decimal separator used depends on the current locale conventions.

Calculations involving float types become inaccurate when it deals with numbers with more than approximately 8 digits long where ever the decimal point is. This is because of how 32bit floats are commonly stored in memory. This means if you rely on float types while working with tiny fractions or large numbers, your calculations can end up between tiny fractions to several trillion off.

Источник

How can I convert all values of an array to floats in PHP?

I am fetching an array of floats from my database but the array I get has converted the values to strings.

How can I convert them into floats again without looping through the array?
Alternatively, how can I fetch the values from the database without converting them to strings?

I am using the Zend Framework and I am using PDO_mysql. The values are stored one per column and that is a requirement so I can’t serialize them.

I can’t floatval the single elements when I use them because I have to pass an array to my flash chart.

The momentary, non-generic solution is to extract the rows and do array_map(‘floatval’,$array) with each row.

php str to float. Смотреть фото php str to float. Смотреть картинку php str to float. Картинка про php str to float. Фото php str to float

php str to float. Смотреть фото php str to float. Смотреть картинку php str to float. Картинка про php str to float. Фото php str to float

5 Answers 5

There is the option PDO::ATTR_STRINGIFY_FETCHES but from what I remember, MySQL always has it as true

Edit: see Bug 44341 which confirms MySQL doesn’t support turning off stringify.

Edit: you can also map a custom function like this:

How are you getting your data? mysql, mysqli or PDO, some other way or even some other database?

you’re probably best of casting to float when you use your value, if you have to. php is likely to do a good job of interpreting it right anyway.

LOL. are you working on the same project I am tharkun?

I just finished (last night) creating something, in a ZF based project, that uses pdo_mysql to retrieve and format data and then output it as xml for use in a flash piece. The values were going in as strings but needed to be floats. Since I’m also the one who wrote the part that gets the data and the one who created the database I just made sure the data was converted to float before it went into the database.

I simply cast the values as float as part of some other formatting, for what it is worth.

Источник

strval

(PHP 4, PHP 5, PHP 7, PHP 8)

strval — Возвращает строковое значение переменной

Описание

Возвращает строковое значение переменной. Смотрите документацию по типу string для более подробной информации о преобразовании в строку.

Список параметров

Переменная, которую необходимо преобразовать в строку.

value может быть любого скалярного типа или объектом, который реализует метод __toString(). strval() нельзя применить к массиву или объекту, которые не реализуют метод __toString().

Возвращаемые значения

Примеры

Пример #1 Пример использования strval() с магическим методом PHP __toString().

class StrValTest
<
public function __toString ()
<
return __CLASS__ ;
>
>

// Выводит ‘StrValTest’
echo strval (new StrValTest );
?>

Смотрите также

User Contributed Notes 8 notes

Some notes about how this function has changed over time, with regards the following statement:

> You cannot use strval() on arrays or on objects that
> do not implement the __toString() method.

In PHP 5.3 and below, strval(array(1, 2, 3)) would return the string «Array» without any sort of error occurring.

From 5.4 and above, the return value is unchanged but you will now get a notice-level error: «Array to string conversion».

For objects that do not implement __toString(), the behaviour has varied:

PHP 4: «Object»
PHP 5 = 5.2: Catchable fatal error: Object of class X could not be converted to string

Note on use of fmod()
I used the floating point fmod() in preference to the % operator, because % converts the operands to int, corrupting values outside of the range [-2147483648, 2147483647]

I haven’t bothered with «billion» because the word means 10e9 or 10e12 depending who you ask.

The function returns ‘#’ if the argument does not represent a whole number.

The only way to convert a large float to a string is to use printf(‘%0.0f’,$float); instead of strval($float); (php 5.1.4).

// strval() will lose digits around pow(2,45);
echo pow(2,50); // 1.1258999068426E+015
echo (string)pow(2,50); // 1.1258999068426E+015
echo strval(pow(2,50)); // 1.1258999068426E+015

// full conversion
printf(‘%0.0f’,pow(2,50)); // 112589906846624
echo sprintf(‘%0.0f’,pow(2,50)); // 112589906846624

I can’t help being surprised that

evaluates to true. It’s the same with strval and single quotes.
=== avoids it.

Why does it matter? One of my suppliers, unbelievably, uses 0 to mean standard discount and 0.00 to mean no discount in their stock files.

It seems that one is being treated as an unsigned large int (32 bit), and the other as a signed large int (which has rolled over/under).

As of PHP 5.1.4 (I have not tested it in later versions), the strval function does not attempt to invoke the __toString method when it encounters an object. This simple wrapper function will handle this circumstance for you:

__toString());
else
return strval($value);
>

In complement to Tom Nicholson’s contribution, here is the french version (actually it’s possible to change the language, but you should check the syntax 😉 )

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *