round in PHP shows scientific notation instead of full number - php

I'm trying to do an echo of a variable containing 1400000.
so there is written: echo round(1400000);
this gives 1,4E+6 instead of the full number.
Anybody an idea on how to display it fully?

It seems that round was the problem.
I changed it with number_format() and this does the job just fine.
Thanks Aron and Paul for the answers.

Related to your question, I also came across this comment on the PHP website.
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:
for( $tmp = 0, $i = 0; $i < 100; $i++ )
{
$tmp += 100000;
echo round($tmp),"\n";
}
So, if you add two floats, end up with
a "special" value, e.g. 1.2E+6, then
put that value unmodified into an
update query to store the value in a
decimal column, say, you will likely
get a failed transaction, since the
database will see "1.2E+6" as varchar
data, not decimal. Likewise, you will
likely get an XSD validation error if
you put the value into xml.
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.
It seems there has not been a "real" fix yet, but judging from the comments in the bug report Paul Dixon referered to earlier, his solution seems to work.

Possibly related to this bug report, so you could try
printf("%d", $myvar);

Related

PHP round() function does not round the number

It looks like PHP round() does not behave as expected. Look at the following code:
log_rec("BEFORE ROUNDING","x", $x);
$x = round($x, 3);
log_rec("AFTER ROUNDING","x", $x);
where log_rec() is simply a function of mine to write a record in a log file,
and $x value is initially set to 3.339999999999999857891452847979962825775146484375.
I expect $x to be 3.34 after rounding.
Here is the result in log file:
▶"BEFORE ROUNDING"■"x"■3.339999999999999857891452847979962825775146484375■
▶"AFTER ROUNDING"■"x"■3.339999999999999857891452847979962825775146484375■
No change. What am I doing wrong? I am using PHP 7.4.26.
NOTE: I need to round the number, that is, to obtain another float number. So, number_format() is not a solution.
UPDATE
I decided to use a different approach, that is to use
log_rec("BEFORE ROUNDING","x", $x);
$x= intval(100 * $x)/100;
log_rec("AFTER ROUNDING","x", $x);
I expected now
▶"BEFORE ROUNDING"■"x"■3.339999999999999857891452847979962825775146484375■
▶"AFTER ROUNDING"■"x"■3.34■
but I still get
▶"BEFORE ROUNDING"■"x"■3.339999999999999857891452847979962825775146484375■
▶"AFTER ROUNDING"■"x"■3.339999999999999857891452847979962825775146484375■
Now I am totally confused. This is a sequence of three well defined instructions. No other code should create some collateral effect.
Any idea?
PS: WHERE THE NUMBER COMES FROM?
Someone asked where that big number comes from.
From a JSON file. What is strange is that that number in JSON is 3.334, but after json_decode() something strange happens: if I use var_dump() I get 3.334 but if I use print_r() I get that big number.

PHP very small decimals result in error

PHP is erroring out on me when working with small decimals / floats. Take the following code:
$spotPrices['entry'] = 1.6591;
$price['o'] = 1.65908;
$currentresult = $spotPrices['entry'] - $price['o'];
echo $currentresult;
I would expect this to output 0.00002 (the answer). But instead it outputs: -1.99999999999E-5
Why is it doing this and, more importantly, how can I get the correct result?
I've done some searching on the forums and seen that floating points give PHP fits but haven't seen a solution or workaround that seems to answer my question.
My calculator is saying that the result should be 0.00002
use number_format:
$currentresult = number_format($spotPrices['entry'] - $price['o'], 8);
Instead of 0.00002 you get 1.9999999999909E-5 which is 0.000019999999999909. This is due to floating point precision. Precision is platform-dependent. You can read up on it here: http://www.php.net/manual/en/language.types.float.php

Strange math calculations in php

I am trying to make this calculation in php but is giving me wrong result. I think that is right.
And if i do 5000.00 - 100.10 it works, but i want the 5,000.00 to work too.
This is my code:
To create the 5,000.00 i have used number_format(5000, 2).
Aswell to the 100.10
$total = $value1 - $value2;
echo $total;
?>
$total = -95.00
I am trying to make this calculation in php but is giving me wrong result. I think that is right.
And if i do 5000.00 - 100.10 it works, but i want the 5,000.00 to work too.
Please Help...
If you want to do arithmetic on number, you can't have the thousands separator (,). What's happening is 5,000.00 is being read as 5 (it stops interpreting it as a number as soon as it hits the comma) and then you're getting 5 - 100.10 which is -95.10 (I'm thinking you left off the .10 in your example.
You'll need to convert first:
$value1 = floatval(str_replace(',', '', $original_value1))
$value2 = floatval(str_replace(',', '', $original_value2))
I'm assuming here that you have them as strings originally. These remove the comma separator.
It sounds like you're confusing rendering in the UI with calculations.
It's perfectly reasonable for a user to see currencies rendered according to their locale rules (e.g. a String "$1,000.00" in USA), but the calculations in the back need to done on a floating point number (e.g. 1000.0).
So you have to be able to convert back and forth between them. You can't make arithmetic operations work on a String. Better to parse the String to a float, do the operations, then convert that back to String for rendering.

How to iterate over a bit value?

I want to build a chessboard via bitboard system.
Starting with 12 bitboards i want to display a table (chessboard), during loop/iteration a piece must be drawn.
How do i loop through all bitvalues?
I was thinking of something like:
for(i=0;i<64;i++)
draw table / build array / draw empty square
These are my my values to start a game:
function init_game($whitePlayer,$blackPlayer)
{
$WhitePawns = '0000000000000000000000000000000000000000000000001111111100000000';
$WhiteKnights = '0000000000000000000000000000000000000000000000000000000001000010';
$WhiteBishops = '0000000000000000000000000000000000000000000000000000000000100100';
$WhiteRooks = '0000000000000000000000000000000000000000000000000000000010000001';
$WhiteQueens = '0000000000000000000000000000000000000000000000000000000000010000';
$WhiteKing = '0000000000000000000000000000000000000000000000000000000000001000';
$BlackPawns = '0000000011111111000000000000000000000000000000000000000000000000';
$BlackKnights = '0100001000000000000000000000000000000000000000000000000001000010';
$BlackBishops = '0010010000000000000000000000000000000000000000000000000000100100';
$BlackRooks = '1000000100000000000000000000000000000000000000000000000000000000';
$BlackQueens = '0000100000000000000000000000000000000000000000000000000000000000';
$BlackKing = '0001000000000000000000000000000000000000000000000000000000000000';
$WhitePieces = $WhitePawns|$WhiteKnights|$WhiteBishops|$WhiteRooks|$WhiteQueens|$WhiteKing;
$BlackPieces = $BlackPawns|$BlackKnights|$BlackBishops|$BlackRooks|$BlackQueens|$BlackKing;
}
Some people asked me: why bitboard appoach?
Answer:
About bitboard
A bitboard, often used for boardgames such as chess, checkers and othello, is a specialization of the bitset data structure, where each bit represents a game position or state, designed for optimization of speed and/or memory or disk use in mass calculations. Bits in the same bitboard relate to each other in the rules of the game often forming a game position when taken together. Other bitboards are commonly used as masks to transform or answer queries about positions. The "game" may be any game-like system where information is tightly packed in a structured form with "rules" affecting how the individual units or pieces relate.
First you have to check if your PHP version supports 64bit integers, otherwise you will have strange results.
Just run:
echo PHP_INT_MAX;
and if result is 9223372036854775807 then it should work.
You're using strings and I suppose that when you'll do $string | $string in form like you're doing it above then it will be cast as integer with base 10, so the result won't be what you want. Since PHP 5.4 you can use 0b000 notation, for lower PHP version you'll need to keep it in hexadecimal or base 10 format. If you're storing values in DB or somewhere like that and you'll receive value as string or you just want to keep it in format presented above, then you have to use intVal($value, 2) first to cast it properly.
To iterate over the value you can use just for loop (as you suggested):
$value = intVal($WhitePieces,2);
for ($i = 0 ; $i < 64 ; ++$i) {
if ((pow(2,$i) & $value)) {
// draw piece
}
}
You do not have bitvalues, you do have strings. And strings should be difficult to or.
How do you loop? Use an array and foreach.
How do you use 64bit values? Use PHP 5.4 and the binary number format: 0b00001111 => 16 - alternatively express the integer value as hex or decimal, which should be completely ok for a game setup routine that will not change because the rules are known for centuries.
Remember that you have to use a 64Bit system to execute your code, otherwise PHP will be unable to support 64Bit integers, and either treat them as float values, or shorten them to 32Bit values, depending on what you actually do.
Because of all this, I'd suggest NOT to use bit fields for the solution. They seem like a great idea to program more assembler-like, but you are not writing assembler, and will probably pay for this approach with non-optimal performance compared to anything else.

PHP Ignoring Digits to the Right of the Decimal Point in Equation

I have a variable $x whose value is read in from an XML file. The value being read from the XML is 1.963788, nothing more, nothing less. When I output $x, I see that the value in $x is in fact 1.963788. All is right with the world.
But then when I use x in an equation such as
$pl = $x*125.0-200.0;
The value of $pl ends up being -75. For whatever reason, PHP seems to be ignoring, or just getting rid of, the digits to the right of the decimal point in $x, which makes $x contain 1. I thought maybe there was a snowball's chance in hell that this occurred in other languages too, so I wrote it up in C++ and, big surprise, I get the right answer of 45.4735.
Anyone ever encountered this before or know what's going on? Thanks.
Have you tried using floatval?
Maybe PHP interprets your number as a string and the standard conversion just casts it to integer.
It probably is due to the fact that $x is being interpreted as a string, and converted to an integer and not a float value.
Try:
$pl = (float) $x * 125.0 - 200.0;
Your number appears to have failed casting as a float. If I use '1,963788' I get your result. If I use '2,963788' I receive a result of 50. According to the PHP docs for intval (and that's what it appears PHP is trying to cast this as, an integer):
Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of integer casting apply.
Check the value $x actually has carefully. It may not be what you expect since PHP seems to disagree that it is, in fact, a float or it would have typed it as such.
Just before you compute $pl, do a var_dump on $x to see what is the actual value stored in it. I've tried your code and it is returning the correct value 45.4735, so I might not be PHP's fault.

Categories