Viewed   179 times

How can I convert from bytes to float in php? Like in Java

int i = (byte3 & 0xff) << 24 | (byte2 & 0xff) << 16 | (byte1 & 0xff) << 8 | byte0 & 0xff; 
Float.intBitsToFloat(i);

 Answers

5

There may be a more direct way, but here you go:

<?php
var_dump(unpack('f', pack('i', 1059760811)));
?>

This is, of course, machine dependent, but I don't know of any machine running PHP that doesn't use IEEE 754 floats.

Saturday, October 8, 2022
 
bea
 
bea
5

The problem is that floats are expected to be in the English format with a . separating the decimal part, not a comma. If the format is always the same with a single comma, use this:

$float = (float)str_replace(',', '.', $value);
Saturday, October 22, 2022
 
3

You aren't doing anything wrong. Floats are notoriously innaccurate. From the docs (In the huge red warning box):

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Friday, October 14, 2022
 
tami
 
4

great example here:

>> dataL = typecast(uint8([189, 33, 136, 147]), 'uint32')
dataL =
   2475172285
>> dataF = double(dataL)
dataF =
   2.4752e+09

big to little, try swapbytes

>> dataLbig = swapbytes(dataL)
dataLbig =
   3173091475
>> dataFbig = double(dataLbig)
dataFbig =
   3.1731e+09

Is this what you were expecting?

Sunday, December 11, 2022
 
3

Use function FORMAT SQL 2012+ https://docs.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql

DECLARE  @input float = 4.92    
SELECT FORMAT(FLOOR(@input)*100 + (@input-FLOOR(@input))*60,'00:00')
Wednesday, November 30, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :