PHP, Convert any number to float 0.x - php

I need to do this rather strange thing, let's say i have:
$number = rand(1, 9);
(This is just an example of what number it could be, in reality i get it in entirely different way)
And now i need "convert" that number to 0.2 or whatever number i got, basically it has to begin with 0 and be a float type of number.

PHP does not support explicit type casting in variable declaration. To convert the int to a float in the way you want to simply divide by 10:
$number = rand(1, 9) / 10;
See this page on PHP Type Juggling for more info. If you mix floats and ints or other types they will be re-casted. Exmple:
echo 10 + 2.5; // gives you 12.5, a float because of the types used
Edit: PHP does have explicit type casting, just not in variable declaration. But even if you cast an integer as a float, it won't display with a decimal place. To do that use PHP's number_format function instead:
echo number_format(10, 1); // gives you 10.0
Edit 2: If you simply want to make your number a decimal between 0 and 1 (such that 2 becomes 0.2, 25 becomes 0.25, etc.) you could use the following function:
function getNumAsDecimal($num) {
return ($num / pow(10, strlen((string)$num)));
}
So getNumAsDecimal(2) would return 0.2.

function Floatize(){
return (float) (rand(1, 9) / 10);
}
echo Floatize(); // will return something like 0.2 or 0.5 or 0.9

$number=(float)rand(1, 9)/10;
See PHP type casting.

Related

Always round up on first decimal

I want my variable's first decimal to always be rounded up. For example:
9.66 goes to 9.7
9.55 goes to 9.6
9.51 goes to 9.6
9.00000001 goes to 9.1
How do I do this?
Use round() with an optional precision and round type arguments, e.g.:
round($value, 1, PHP_ROUND_HALF_UP)
The optional second argument to round() is the precision argument and it specifies the number of decimal digits to round to. The third optional argument specifies the rounding mode. See the PHP manual for round for details.
Using round() does not always round up, even when using PHP_ROUND_HALF_UP (e.g. 9.00001 is not rounded to 9.1). You could instead try to use multiplication, ceil() and division:
ceil($value * 10.0) / 10.0
Since these are floating-point values, you might not get exact results.
I made couple tests and suggest the following answer with test cases
<?php
echo '9.66 (expected 9.7) => '.myRound(9.66).PHP_EOL;
echo '9.55 (expected 9.6) => '.myRound(9.55).PHP_EOL;
echo '9.51 (expected 9.6) => '.myRound(9.51).PHP_EOL;
echo '9.00000001 (expected 9.1) => '.myRound(9.00000001).PHP_EOL;
echo '9.9 (expected ??) => '.myRound(9.9).PHP_EOL;
echo '9.91 (expected ??) => '.myRound(9.91).PHP_EOL;
function myRound($value)
{
return ceil($value*10)/10;
}
I'm not a php programmer so will have to answer in "steps". The problem you have is the edge case where you have a number with exactly one decimal. (e.g. 9.5)
Here's how you could do it:
Multiply your number by 10.
If that's an integer, then return the original number (that's the edge case), else continue as follows:
Add 0.5
Round that in the normal way to an integer (i.e. "a.5" rounds up).
Divide the result by 10.
For step (2), sniffing around the php documentation reveals a function bool is_int ( mixed $var ) to test for an integer.
You will need a custom ceil() function, your requirements cannot be satisfied by the default function or by the round.
Use this: online test
You can use this technique. Just explode the given number / string, get the number which is next value / digit of the .. after getting this you need to increment that value and check if the value is greater than 9 or nor, if then divide that and add the carry to the first portion of the main number.
$var = '9.96';
$ar = explode(".", $var);
$nxt = substr($ar[1], 0, 1) + 1;
if($nxt > 9){
$tmp = (string) $nxt;
$num = floatval(($ar[0] + $tmp[0]).".".$tmp[1]);
}
else
$num = floatval($ar[0].".".$nxt);
var_dump($num); // float(10)

PHP idiom for a counter over non-negative ints

In trying to make a counter that returns to 0 when the int range is exhausted. Essentially, 0, 1, ..., MAX_INT - 1, MAX_INT, 0, 1, ...
The idiomatic C is
x = ((x + 1) & MAX_INT);
But this won't work in PHP because the int gets promoted to a double when it overflows. The cleanest I can come up with is x = x == PHP_INT_MAX ? 0 : x + 1, but it's messier.
This seems to work:
$x = ($x + 1) % (PHP_INT_MAX+1);
You can use intval() to force using integers:
$x = intval($x + 1) & PHP_INT_MAX;
Try it out: echo intval(PHP_INT_MAX + 1): https://3v4l.org/7jlPN
Update:
The manual on Converting to integer states:
If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31 on 32-bit platforms and +/- 9.22e+18 = 2^63 on 64-bit platforms other than Windows), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!
So you are right, while this is consistent for current implementations, the result is specified to be undefined and you should not rely on it.
That leaves you with more verbose solutions, either with % modulus or the ternary conditional as you already have it (which I would prefer for clarity and robustness).

How do I truncate a decimal in PHP?

I know of the PHP function floor() but that doesn't work how I want it to in negative numbers.
This is how floor works
floor( 1234.567); // 1234
floor(-1234.567); // -1235
This is what I WANT
truncate( 1234.567); // 1234
truncate(-1234.567); // -1234
Is there a PHP function that will return -1234?
I know I could do this but I'm hoping for a single built-in function
$num = -1234.567;
echo $num >= 0 ? floor($num) : ceil($num);
Yes intval
intval(1234.567);
intval(-1234.567);
Truncate floats with specific precision:
echo bcdiv(2.56789, 1, 1); // 2.5
echo bcdiv(2.56789, 1, 3); // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 3); // -2.567
This method solve the problem with round() function.
Also you can use typecasting (no need to use functions),
(int) 1234.567; // 1234
(int) -1234.567; // -1234
http://php.net/manual/en/language.types.type-juggling.php
You can see the difference between intval and (int) typecasting from here.
another hack is using prefix ~~ :
echo ~~1234.567; // 1234
echo ~~-1234.567; // 1234
it's simpler and faster
Tilde ~ is bitwise NOT operator in PHP and Javascript
Double tilde(~) is a quick way to cast variable as integer, where it is called 'two tildes' to indicate a form of double negation.
It removes everything after the decimal point because the bitwise operators implicitly convert their operands to signed 32-bit integers. This works whether the operands are (floating-point) numbers or strings, and the result is a number
reference:
https://en.wikipedia.org/wiki/Double_tilde
What does ~~ ("double tilde") do in Javascript?
you can use intval(number); but if your number bigger than 2147483648 (and your machine/os is x64) all bigs will be truncated to 2147483648. So you can use
if($number < 0 )
$res = round($number);
else
$res = floor($number);
echo $res;
You can shift the decimal to the desired place, intval, and shift back:
function truncate($number, $precision = 0) {
// warning: precision is limited by the size of the int type
$shift = pow(10, $precision);
return intval($number * $shift)/$shift;
}
Note the warning about size of int -- this is because $number is potentially being multiplied by a large number ($shift) which could make the resulting number too large to be stored as an integer type. Possibly converting to floating point might be better.
You could get fancy with a $base parameter, and sending that to intval(...).
Could (should) also get fancy with error/bounds checking.
An alternative approach would be to treat number as a string, find the decimal point and do a substring at the appropriate place after the decimal based on the desired precision. Relatively speaking, that won't be fast.

How to convert float value to integer in php?

I want to convert float value (Eg:1.0000124668092E+14) to Integer in php,what is the best method for this in php.output should be "100001246680920"
What do you mean by converting?
casting*: (int) $float or intval($float)
truncating: floor($float) (down) or ceil($float) (up)
rounding: round($float) - has additional modes, see PHP_ROUND_HALF_... constants
*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.
PHP_INT_MAX: The largest integer supported in this build of PHP. Usually int(2147483647).
But, you could use the BCMath, or the GMP extensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)
I just want to WARN you about:
>>> (int) (290.15 * 100);
=> 29014
>>> (int) round((290.15 * 100), 0);
=> 29015
Use round()
$float_val = 4.5;
echo round($float_val);
You can also set param for precision and rounding mode, for more info
Update (According to your updated question):
$float_val = 1.0000124668092E+14;
printf('%.0f', $float_val / 1E+14); //Output Rounds Of To 1000012466809201
There is always intval() - Not sure if this is what you were looking for...
example: -
$floatValue = 4.5;
echo intval($floatValue); // Returns 4
It won't round off the value to an integer, but will strip out the decimal and trailing digits, and return the integer before the decimal.
Here is some documentation for this: -
http://php.net/manual/en/function.intval.php
Try this
<?php
$float_val = 1.0000124668092E+14;
echo intval($float_val);
?>
Use round, floor or ceil methods to round it to the closest integer, along with intval() which is limited.
http://php.net/manual/en/function.round.php
http://php.net/manual/en/function.ceil.php
http://php.net/manual/en/function.floor.php

What would be the best way to detect if a float has a zero fraction value (e.g. 125.00) in PHP?

See, I want to write a function that takes a float number parameter and rounds the float to the nearest currency value (a float with two decimal places) but if the float parameter has a zero fraction (that is, all zeroes behind the decimal place) then it returns the float as an integer (or i.e. truncates the decimal part since they're all zeroes anyways.).
However, I'm finding that I can't figure out how to determine if if a fraction has a zero fraction. I don't know if there's a PHP function that already does this. I've looked. The best I can think of is to convert the float number into an integer by casting it first and then subtract the integer part from the float and then check if the difference equals to zero or not.
if($value == round($value))
{
//no decimal, go ahead and truncate.
}
This example compares the value to itself, rounded to 0 decimal places. If the value rounded is the same as the value, you've got no decimal fraction. Plain and simple.
A little trick with PHPs type juggling abilities
if ($a == (int) $a) {
// $a has a zero fraction value
}
I think the best way:
if ((string)$value == (int)$value){
...
}
Example:
$value = 2.22 * 100;
var_dump($value == (int)$value); // false - WRONG!
var_dump($value == round($value)); // false - WRONG!
var_dump((string)$value == (int)$value); // true - OK!
function whatyouneed($number) {
$decimals = 2;
printf("%.".($number == (int)($number) ? '0' : $decimals)."F", $number);
}
So basically it's either printf("%.2F") if you want 2 decimals and printf("%.2F") if you want none.
Well, the problem is that floats aren't exact. Read here if you're interested in finding out why. What I would do is decide on a level of accuracy, for example, 3 decimal places, and base exactness on that. To do that, you multiply it by 1000, cast it to an int, and then check if $your_number % 1000==0.
$mynumber = round($mynumber *1000);
if ($mynumber % 1000==0)
{ isInt() }
Just so you know, you don't have to write a function to do that, there's already one that exists:
$roundedFloat = (float)number_format("1234.1264", 2, ".", ""); // 1234.13
If you want to keep the trailing .00, just omit the float cast (although it will return a string):
$roundedFloatStr = number_format("1234.000", 2, ".", ""); // 1234.00

Categories