php floatval 2 знака

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.

Источник

number_format

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

number_format — Форматирует число с разделением групп

Описание

Форматирует число сгруппированными тысячами и, возможно, десятичными цифрами.

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

Устанавливает разделитель дробной части.

Устанавливает разделитель тысяч.

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

Список изменений

Примеры

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

Во Франции обычно используются 2 знака после запятой (‘,’), и пробел (‘ ‘) в качестве разделителя групп. Этот пример демонстрирует различные способы форматирования чисел:

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

User Contributed Notes 38 notes

It’s not explicitly documented; number_format also rounds:

Outputs a human readable number.

if you want to benchmark all costs for 5 seconds:

(with ms meaning milliseconds and s meaning seconds)

I ran across an issue where I wanted to keep the entered precision of a real value, without arbitrarily rounding off what the user had submitted.

I figured it out with a quick explode on the number before formatting. I could then format either side of the decimal.

You can change %03d to %04d, etc.

See also the documentation for localeconv, which will provide values for decimal point and thousands separator from the C standard library.

Of course localeconv features many more locale information, like indicating to put the negative sign behind the value for some locale settings which can’t be used to customize present number_format.

Simple function to show money as only dollars if no cents, but will show 2 decimals if cents exist.

The ‘cents’ flag can force to never or always show 2 decimals

And remember to always contribute custom functions if they might be useful to the rest of us or future versions of the php language.

Just an observation:
The number_format rounds the value of the variable.

$val1 = 1.233;
$val2 = 1.235;
$val3 = 1.237;

echo number_format($val1,2,»,»,».»); // returns: 1,23
echo number_format($val2,2,»,»,».»); // returns: 1,24
echo number_format($val3,2,»,»,».»); // returns: 1,24

//again check through array for non numerical characters but skipping allready processed keys
//if is not number remove from array

// Here is a function that produces the same output as number_format() but also works with numbers bigger than 2^53.

$original_number= 9223372036854775805;
echo a_number_format($original_number, 4, ‘.’,»‘»,3);
// Outputs: 9’223’372’036’854’775’805.1230

In my function my_number_format() [shown below] there was a bug.

Here is the corrected version:

?>

Thanks to Federico Cassinelli for the bug report.

[EDIT BY danbrown AT php DOT net: The original note follows.]

But I have a problem with that: I want to add commas as thousand separators and change the decimal-separator (this could also be done with str_replace), but I do not want to change the amount of fractional digits!

But since the 2nd argument of number_format is necessary to enter the 3rd and 4th argument, this cannot be done with number_format. You have to change the fractional digits with this function.

But I want that 1234.56 changes into 1.234,56 and 1234.567890123456 changes into 1.234,567890123456

So, I created following function, that doesn’t change the amount of fractional digits:

A simple funtion to format american dollars.

To prevent the rounding that occurs when next digit after last significant decimal is 5 (mentioned by several people below):

What do you do if some of your numbers have decimal places, and some don’t? You can switch between functions, but if you’re building it in a loop, that’s not a good solution. Instead, we have the same as below, with a slight change:

function number_format_unlimited_precision($number,$decimal = ‘.’) <
$broken_number = explode($decimal,$number);
if($broken_number[1]==0) <
return number_format($broken_number[0]);
>else <
return number_format($broken_number[0]).$decimal.$broken_number[1];
>;
>;

formatting numbers may be more easy if u use number_format function.

I also wrote this :
function something($number)
<
$locale = localeconv();
return number_format($number,
$locale[‘frac_digits’],
$locale[‘decimal_point’],
$locale[‘thousands_sep’]);
>

function formats numbers of datetime type,

[ «zaman» ]= «1983-8-28 5:5:5» ;

Don’t forget to specify thousands_sep that default is ‘,’ to another value, otherwise function will return null.

This way, I use my 1st variable for calculations and my 2nd variable for output. I’m sure there are better ways to do it, but this got me back on track.

simpler function to convert a number in bytes, kilobytes.

?>

you may also add others units over PeraBytes when the hard disks will reach 1024 PB 🙂

If you want a number of digits after the point, but not unnecessary zeros.
Eg.
number_format(1.20000,4) = 1.2000
num_format(1.20000,4,0) = 1.2

number_format(1.20000,4) = 1.2000
num_format(1.20000,4,2) = 1.20

number_format(1.23456,4) = 1.2345
num_format(1.23456,4,2) = 1.2345

I’d like to comment to the old notes of «stm555» and «woodynadobhar».
They wrote about «number_format_unlimited_precision()».
I guess many of us need that kind of function, which is the almost same function as number_format but don’t round a number.

Does Anyone know any new solution in a recent PHP version?

If you use space as a separator, it will break on that space in HTML tables.

Furthermore, number_format doesn’t like ‘ ‘ as a fourth parameter. I wrote the following function to display the numbers in an HTML table.

function to convert numbers to words
indian: thousand,lakh,crore
Note: function can only convert nos upto 99 crores

I’m not sure if this is the right place anyway, but «ben at last dot fm»‘s ordinal function can be simplified further by removing the redundant «floor» (the result of floor is still a float, it’s the «%» that’s converting to int) and outer switch.

Note that this version also returns the number with the suffix on the end, not just the suffix.

This is a simple and useful function to convert a byte number in a KB or MB:

if you want as a separator and use windows charset this piece of code may help:

echo convertNumberToWordsForIndia ( «987654321» );

//Output ==> Indian Rupees Ninty Eight Crores Seventy Six Lakhs Fifty Four Thousand Three Hundred & Twenty One Only.
?>

Источник

floatval

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

Описание

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

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

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

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

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

Примеры

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

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

Коментарии

This function doesn’t seem to add any functionality that wasn’t already there.

This function converts a string to a float no matter is the decimal separator dot (.) or comma (,). It also converts integers correctly. It takes the digits from the beginning of the string and ignores all other characters.

floatval() does not work with «$35,234.43», as it could not handle the ‘$’ and the ‘,’. The following takes care of all values, such that only numeric and the decimal sign are input into floatval(). (It probably shows I’m an old ‘c’ guy). this function only lightly tested.

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

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

Use this snippet to extract any float out of a string. You can choose how a single dot is treated with the (bool) ‘single_dot_as_decimal’ directive.
This function should be able to cover almost all floats that appear in an european environment.

else
<
// No number found, return zero
return 0 ;
>
>

echo float ( ‘foo 123,00 bar’ ); // returns 123.00
echo float ( ‘foo 123.00 bar’ array( ‘single_dot_as_decimal’ => TRUE )); //returns 123.000
echo float ( ‘foo 123.00 bar’ array( ‘single_dot_as_decimal’ => FALSE )); //returns 123000
echo float ( ‘foo 222.123.00 bar’ array( ‘single_dot_as_decimal’ => TRUE )); //returns 222123000
echo float ( ‘foo 222.123.00 bar’ array( ‘single_dot_as_decimal’ => FALSE )); //returns 222123000

// The decimal part can also consist of ‘-‘
echo float ( ‘foo 123,— bar’ ); // returns 123.00

you can also use typecasting instead of functions:

@pillepop2003 at yahoo dot de

For those of you, who are looking for a function that rips the first,
but longest possible float (or at least integer) from a string,
like 123.45 from the string «Price: 123,45$»

If no useable value is found, the function returns false.

Checks for both comma and dot as decimal-separator,
but does not check for 3 digits between thousands,
so 1,234.5 is as valid as 1,23,4.5 (both will return 1234.5)

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

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();

echo »

» ;

After using floatvalue() you can go forward with number_format() as usual.

i noticed all (well, unless i missed something) the functions working with decimals destroy trailing decimal places. this function restores them in case you want to be able to display a consistent precision for users.

locale aware floatval:

setlocale() and floatval() duo could break your DB queries in a very simple way:

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.

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)

There is much easier way to deal with formatted numbers:

= ‘1.299,00 EUR’ ;
//$price = ‘EUR 1.299,00’;
//$price = ‘$1,745.09’;
//$price = ‘$14’;
//$price = ‘$.14’;

Be aware the last tofloat($num).

In theory it is very useful to have a function «separator-agnostic» (I think «locale based» solutions are useless if you have to parse a user file that can have a locale different to the server).

But this can lead to misinterpretations; in short: «123,456» is «123.456» (so comma used as decimal separator) or «123456» (comma used as thousand separator).

In any case, if you really want to use it, please don’t forget that this function doesn’t manage negative numbers.

Float value less than 0.0001 (0.0000999999999999995) will be converted by floatval to scientific notation (exponential notation):
( floatval ( 0.0000999999999999995 )); # >> float(0,0001)

var_dump ( floatval ( «0.000099» )); # >> float(9.9E-5)

var_dump ((string) floatval ( 0.000099 )); # >> string(6) «9.9E-5»

I get the following disturbing results:
var_dump string(10) «0.01333»
echo the string=0.01333
echo (float)string=0
echo floatval(string)=0

The string is an outcome of array_map(‘str_getcsv’, file(.
I can’t find the characters 8-10

(float) would be more performant here (up to 6x times faster).

Источник

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 floatval 2 знака. Смотреть фото php floatval 2 знака. Смотреть картинку php floatval 2 знака. Картинка про php floatval 2 знака. Фото php floatval 2 знака

This is much more reliable.

php floatval 2 знака. Смотреть фото php floatval 2 знака. Смотреть картинку php floatval 2 знака. Картинка про php floatval 2 знака. Фото php floatval 2 знака

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 floatval 2 знака. Смотреть фото php floatval 2 знака. Смотреть картинку php floatval 2 знака. Картинка про php floatval 2 знака. Фото php floatval 2 знака

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.

Источник

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

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

Stringfloatval()getFloat()parseFloat()