I have the following code in a PHP script:
$sol = mt_rand(1,3);
I thought this was meant to return an integer but instead I'm getting a number with about 6 decimal places. How can I force it to return 1,2 or 3?
Thanks
You can use the ceiling or floor functions to round to an integer.
$sol = floor(mt_rand(1, 3));
$sol = ceil(mt_rand(1, 3));
Related
I am trying to receive a result of a math operation with small numbers (maximum 8 decimals), I receive a float result, but in a format that make the other numbers stay with an error:
$a = round($x, 8); //returns 0.0478674, that's correct
$b = round($y,8); //returns 0.04786261, that's correct
$z = $a - $b; //z returns 4.7899999999976E-6, and not 0.00000479 as I was expecting
I tried as well
$w = round($z,8); //but w returns 4.79E-6, and not 0.00000479 as I was expecting
My problem is because the number 4.7899999999976E-6 give an error in other calcs and it's a ugly number to show to the user.
How can I make this number be 0.00000479?
you can use number_format:
$w = number_format($z,8);
number_format should do what you require, from the help: https://www.php.net/manual/en/function.number-format.php
For your specific requirement here:
$w = number_format($z,8);
Need to round 30.61 to 30.60, Any built-in function for PHP to do this ?
If I understand your desired output correctly, that you only want to round the second decimal point, you can round with 1 decimal presicion, then use numer_format() to ensure you get the correct number of decimals.
$num = 30.61;
echo number_format(round($num, 1), 2);
round() documentation
number_format() documentation
Live demo
you can do this
$num = 3.61;
/*round to nearest decimal place*/
$test_number = round($num,1);
/* ans :3.6
format to 2 decimal place*/
$test_number = sprintf ("%.2f", $test_number);
/* ans : 3.60 */
I want to round a number and I need a proper integer because I want to use it as an array key. The first "solution" that comes to mind is:
$key = (int)round($number)
However, I am unsure if this will always work. As far as I know (int) just truncates any decimals and since round($number) returns a float with theoretically limited precision, is it possible that round($number) returns something like 7.999999... and then $key is 7 instead of 8?
If this problem actually exists (I don't know how to test for it), how can it be solved? Maybe:
$key = (int)(round($number) + 0.0000000000000000001) // number of zeros chosen arbitrarily
Is there a better solution than this?
To round floats properly, you can use:
ceil($number): round up
round($number, 0): round to the nearest integer
floor($number): round down
Those functions return float, but from Niet the Dark Absol comment: "Integers stored within floats are always accurate, up to around 2^51, which is much more than can be stored in an int anyway."
round(), without a precision set always rounds to the nearest whole number. By default, round rounds to zero decimal places.
So:
$int = 8.998988776636;
round($int) //Will always be 9
$int = 8.344473773737377474;
round($int) //will always be 8
So, if your goal is to use this as a key for an array, this should be fine.
You can, of course, use modes and precision to specify exactly how you want round() to behave. See this.
UPDATE
You might actually be more interested in intval:
echo intval(round(4.7)); //returns int 5
echo intval(round(4.3)); // returns int 4
What about simply adding 1/2 before casting to an int?
eg:
$int = (int) ($float + 0.5);
This should give a predictable result.
Integers stored within floats are always accurate, up to around 253, which is much more than can be stored in an int anyway. I am worrying over nothing.
For My Case, I have to make whole number by float or decimal type
number. By these way i solved my problem. Hope It works For You.
$value1 = "46.2";
$value2 = "46.8";
// If we print by round()
echo round( $value1 ); //return float 46.0
echo round( $value2 ); //return float 47.0
// To Get the integer value
echo intval(round( $value1 )); // return int 46
echo intval(round( $value2 )); // return int 47
My solution:
function money_round(float $val, int $precision = 0): float|int
{
$pow = pow(10, $precision);
$result = (float)(intval((string)($val * $pow)) / $pow);
if (str_contains((string)$result, '.')) {
return (float)(intval((string)($val * $pow)) / $pow);
}
else {
return (int)(intval((string)($val * $pow)) / $pow);
}
}
Round to the nearest integer
$key = round($number, 0);
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.
I am trying to round down a number using PHP's round() function. Here is the code I am using:
$line_item_price = 13.775;
echo round($line_item_price, 2, PHP_ROUND_HALF_DOWN);
Now when I run the code like this I am hoping to get the output 13.77, except I am getting 0 (or nothing -- not sure which yet).
Now when I remove the PHP_ROUND_HALF_DOWN I get 13.78. Anyone see what I am doing wrong here? It seems like this should be working correctly.
The mode parameter was introduced in version 5.3, therefore it will not work for you. You'll have to find a custom function to do what you are looking for.
You are using a function that is not yet available in your current version of PHP. One way to solve this problem is using the floor function.
$line_item_price = 13.775;
echo floor($line_item_price * 100) / 100;
What I'm doing here is too first multiply the value with 100 and then floor the value. This will give you a rounded down value with the precision of 2. Then to get the correct value you need to devide with 100.
The number 100 comes from the power(10, desired precision)
can you not just do:
echo round($line_item_price, 2)
?
I'm not 100% sure but I think the ROUND_HALF_DOWN etc are for fractions such as 1.5, 2.5 and integers.
Here is a way to do it:
$num = 13.775;
$tmp = intval($num*1000);
$dec = $tmp % 10;
if ($dec > 5) {
$rounded = (1+intval($tmp/10))/100;
} else {
$rounded = intval($tmp/10)/100;
}
echo $rounded,"\n";
This gives : 13.77 for $num=13.775 and 13.78 for $num=13.776
Actually, I'm kind of surprised that it works at all, since the number 13.775 is not exactly representable in floating point:
$ php -r 'printf("%.40f\n", 13.775);'
13.7750000000000003552713678800500929355621
Indeed, it seems that round() is a bit lax about what counts as "half":
$ php -r 'echo round(13.77500000000001, 2, PHP_ROUND_HALF_DOWN) . "\n";'
13.77
Anyway, if your PHP doesn't support PHP_ROUND_HALF_DOWN, here's a simple kluge that gives approximately the same functionality:
function round_half_down ( $num, $digits ) {
$mul = pow( 10, $digits );
return ceil( $num * $mul - 0.5 ) / $mul;
}
This does turn out to work as one would naively expect, but is slightly stricter than round(): round_half_down(13.775, 2) == 13.77, but round_half_down(13.77500000000001, 2) == 13.78. Also, as a curious edge case, round_half_down(0.001, 2) returns -0. If you don't like that, you can always pass the return value through sprintf("%.{$digits}F") to format it nicely.