I have a code where I got some numbers like this:
92.682926829268
I'd like to cut them like this:
92.68
This is my code:
<td><?php if (($row['TotalMatch']) > 10){ echo ($row['OK_05'] / $row['TotalMatch']) * 100; } ?></td>
I tried with floor and round but I get that example I showed at the beginning of post ( 92.682926829268 instead of 92.68 )
Thanks for your attention
Regards!
EDIT Could you give me an example with my code? Thanks
Use sprintf() to format the number.
echo sprintf("%.2f", 92.682926829268);
Example:
https://3v4l.org/U87T9
The expression you're trying to format is this:
($row['OK_05'] / $row['TotalMatch']) * 100
So whichever function you decide to use needs to go around that expression.
As to which function to use, you need to select one that returns a string, not a float.
If you use round, and your expression returns a float that rounds to a number with two zeros after the decimal point, the trailing zeros will not be displayed in the result. For example, echo round(92.0006829268, 2) will display 92, not 92.00. So don't use round if you need to be sure that two decimal places are always displayed. round is a math function, not a formatting function.
floor is really not useful at all here, as it returns a number with no decimal places.
A simple way is to use sprintf as shown in some of the other answers.
echo sprintf("%.2f", ($row['OK_05'] / $row['TotalMatch']) * 100);
The first argument to sprintf is "%.2f", which is a format string indicating that the second argument should be displayed as a float with two decimal places. The second argument is your expression.
Using bcdiv as suggested in the other answer will also work, but it works a little differently that sprintf and will produce a slightly different result in some cases.
sprintf will round to the number of decimal places specified, so for example
echo sprintf("%.2f", 926.89 / 10); // outputs 92.69
and bcdiv will truncate instead, so
echo bcdiv(926.89, 10, 2); // outputs 92.68
Whichever one of those works for you, do that.
You can use the round function
$var = 92.682926829268;
$var = round($var, 2)
Or use sprintf (%.2f cuts the number)
$var = sprintf("%.2f", $var);
Try using sprintf like below:
<?php
$mynumber = 98.343434;
echo sprintf('%.2f', $mynumber); // this will output 98.34
You could use bcdiv()
bcdiv($row['OK_05'], ($row['TotalMatch'] * 100), 2);
Related
I'm trying to format numbers with not decimal points or commas, I've tried number_format() and money_format() and can't seem to get the result I need.
number_format($item->amount,2)
Result: 14,995.00
money_format("%i", $item->amount)
Result: 14,995.00
I'm want to get the following numbers formatted correct.
14995 needs to be £149.95
6795 needs to be £67.95
What is the best way to get the result above?
Using brick/money (disclaimer: I'm the author):
use Brick\Money\Money;
// Instantiating from a decimal amount
$money = Money::of('67.95', 'GBP');
echo $money->formatTo('en_GB'); // £67.95
// Instantiating from a minor amount (cents)
$money = Money::ofMinor(6795, 'GBP');
echo $money->formatTo('en_GB'); // £67.95
setlocale(LC_MONETARY, 'en_GB.UTF-8'); // change if needed
echo money_format('%n', 6795 / 100);
returns
£67.95
for me, so that should work. As i mentioned in my comment, you probably can't get the code to both display 14995 as 1,499.50 (divide by 10) and 6795 as 67.95 (divide by 100), so I'd recommend refactoring the code accordingly.
I am trying to generate a string with exactly 6 random numbers in it. My current code:
$test = sprintf('%6d', rand(1, 1000000));
With this code I get a string that sometimes has an empty value at the beginning like " 53280". I would want to have it produce "053280" in that case. How to achieve this?
You should add a 0 in your conversion specification to indicate that you want zero-padding:
$test = sprintf('%06d', rand(1, 1000000));
// ^-- here
The conversion specifications are documented on the sprintf manual page.
If you don't want to use sprintf (some dont!), an alternative way to do it would be:
$test = str_pad(mt_rand(1, 999999),6,0,STR_PAD_LEFT);
Example output:
736523
024132
003145
Using mt_rand here because its a better random number function (not perfect, but better than just rand). Also adjusted to 999999 since 1000000 could possibly produce a 7 digit number.
Doing a benchmark of 10000 iterations on the three answers provided (Sean, Mine, Aslan), these are the results in speed:
Sean's Method: 0.005
My Method: 0.006
Aslan's Method: 0.009
So you would be better off going with Sean's method.
You can just replace the empty character with 0.
$test = str_replace(" ", "0", sprintf('%6d', rand(1, 1000000)));
I am trying to create an ecommerce store and our prices need to fluctuate with the exchange rate for different countries so I'm dealing with a lot of decimal places.
What I want to do is round the original price to the nearest full number (as in they can keep the change). But then I want to format that as a currency with two decimal places.
<?php
$number = 12345.6789;
echo $number; // outputs '12345.6789'
$number = number_format($number,0);
echo $number; // outputs '12,346'
$number = number_format($number,2);
echo $number; // outputs '12.00'
?>
After formatting to no decimal places it starts reading the ',' as the decimal separator instead of the thousands separator and formats that for two decimal places.
It also gives the following error:
A non well formed numeric value encountered in C:\wamp64\www\Lifting365\test.php on line 6
How can I achieve what I am looking for?
As specified in the documentation, number_format returns a string value, you can't reuse it as a number.
Use the function round() to round your number, if you want to round it to the direct upper integer use ceil() instead.
number_format(round(12345.6789), 2);
// apply intval to get the low integer value (for change purposes)
$number = 12345.6789;
echo $number; // outputs '12345.6789'
echo intval($number)."<br/>"; // outputs '12345'
echo number_format(intval($number),0,'.','.'); // outputs '12.345'
echo number_format(intval($number),0,'.',','); // outputs '12,345'
Use round function and then number_format.
// returns 12,346.00
number_format(round(12345.6789), 2);
The function number_format accepts 4 parameters. Per default a point will be used as decimal seperator and comma as thousands seperator (12345.6789 become 12,346 after your first call; as excepted). It's not explicitly documented but number_format also rounds.
http://php.net/manual/de/function.number-format.php
string number_format ( float $number , int $decimals = 0 , string $dec_point = "." , string $thousands_sep = "," )
You are getting an error because you reuse the same variable $number. After your first call to number_format you dont have a float value anymore.
<?php
$number = 12345.6789;
echo $number."<br>"; // outputs 12345.6789
echo number_format($number,0)."<br>"; // outputs 12,346
echo number_format($number,2)."<br>"; // outputs 12,345.68
?>
If you are not sure what is in your variable you can apply floatval to it.
echo number_format(floatval($number),2);
The PHP function that you're looking for is money_format() http://php.net/manual/en/function.money-format.php have a good read through the manual page (including the comments)
$quantity = 20;
$product_rate = 66.79;
$total = $quantity * $product_rate;
echo $total;
Output is showing 1335.8000000000002
is there possible to show 1335.8 using php..?
You can use the number_format() function like this:
$firstNum = 1335.8000000000002;
$number = number_format($firstNum, 1, '.', '');
echo $number;
outputs:
1335.8
more on number_format() here: http://php.net/number-format.
You can also multiply the number by 10, then use intval() to convert it to an integer (that way stripping out the decimals) and then divide by 10 like this:
$firstNum = 1335.8000000000002;
$number = 10 * intval($firstNum)/10;
echo $number;
outputs:
1335.8
Note: when using the methods above there will be no rounding, for rounding you would use something like this:
$number = round($firstNum, 1);
echo $number;
which in this case also outputs:
1335.8
Do you really use these variable values? I'm using PHP7 and the output for your given values is 1335.8. If you do a manual calculation it is the same result. It should be 1335.8. Anyway if you need to roundup the value you can use below.
round($total,1);
Please refer the below link and you will be able to grab more details.
http://php.net/manual/en/function.round.php
Because how floating point numbers work, they cannot represent every numbers exactly, so approximations are made.
The closest representation of 20 is 20, it can represent 20 exactly, but 66.79 for instance is approximated to 66.7900000000000062527760746889, that times 20 is 1335.800000000000125055521493778 that again cannot be represented and is approximated to 1335.80000000000018189894035459.
Depending on how you choose to print this number, it may round different ways, in your case for some reason you decided to print 13 decimal places so it rounded to 1335.8000000000002, but if you print only 1 or 2 decimal places it will print as 1335.8 or 1335.80. Just be mindful about that when printing floating point numbers, you may want to specify how many decimal places are relevant to you. For that, use number_format().
Example:
echo number_format($number, 2); // prints 2 decimal places
You can do this simply using echo echo round($total, 1) instead of doing round($total)
Number format adds the commas I want but removes the decimals.
echo number_format("1000000.25");
This returns 1,000,000
I want it to return 1,000,000.25
I need both the commas and the decimals, without any number rounding. All my values are decimals. They vary in length.
Do I have to use something other than number format?
In case what you meant by they vary in length is related to the decimal part, take a look at this code:
function getLen($var){
$tmp = explode('.', $var);
if(count($tmp)>1){
return strlen($tmp[1]);
}
}
$var = '1000000.255555'; // '1000000.25'; // '1000000';
echo number_format($var, getLen($var));
Some tests
Output for 1000000.255555:
1,000,000.255555
Output for 1000000.25:
1,000,000.25
Output for 1000000:
1,000,000
It counts how many chars there are after the . and uses that as argument in the number_format function;
Otherwise just use a constant number instead of the function call.
And some reference...
From the manual -> number_format():
string number_format ( float $number [, int $decimals = 0 ] )
And you can see in the description that
number
The number being formatted.
decimals
Sets the number of decimal points.
And a bit more:
[...]If two parameters are given, number will be formatted with decimals
decimals with a dot (".") in front, and a comma (",") between every
group of thousands.
$number = '1000000.25';
echo number_format($number, strlen(substr(strrchr($number, "."), 1)));
Explanation:
Number Format takes a second parameter which specifies the number of decimal places required as pointed out in the docs. This Stack overflow answer tells you how to get the number of decimal places of your provided string
The docs for number_format() indicate the second parameter is used to specify decimal:
echo number_format('1000000.25', 2);
Ref: http://php.net/manual/en/function.number-format.php