May I know what is the function to be use in order to round up the column value into 2 decimals point with percentage symbol? E.g: 1.88% instead of 1.88230293
$worksheet_details->setCellValue("D14", "=SUM((F33 / F34))");
How do I round up the value in cell D14?
SOLUTION:
By the way, after I keep continue look for the solution from the Internet and I got this...
$percentageFormat = '#.## \%;[Red]-#.## \%';
$worksheet_details->setCellValue("C14", "=SUM((C33 / C34) * 100)");
$worksheet_details->getStyle('C14')->getNumberFormat()->setFormatCode($percentageFormat);
just change the first # to 0 if you want it display in 0.xx format... or else it will display .xx only
If you just want it to be outputted as a string:
echo '%'.number_format($your_number,2);
If you want to retain it as a numerical float value (but compromise on the percentage):
echo round($your_number,2);
If you're looking for an Excel function, use:
$worksheet_details->setCellValue('D14', '=TEXT(F33/F34,"0.00%")');
I guess you are looking for ROUND() function:
=ROUND(10/3; 2)
or, in your case:
$worksheet_details->setCellValue("D14", "=ROUND(SUM((F33 / F34)); 2)");
If you mean to round in PHP, with round() you can specify the precision you want a float number:
echo round(1.95583, 2) . "%"; // 1.96%
If you mean to round in Excel, you can use the ROUND function:
$worksheet_details->setCellValue("D14", "=TEXT(SUM((F33 / F34)), '###.##%')");
or
$worksheet_details->setCellValue("D14", "=TEXT(SUM((F33 / F34)/100), '###.##%')");
if the number is a percentage already.
Hope it helps.
If you want to display in percent number format you can try this.
$percentVal = '95.6';
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
$percentCell->setValue($percentVal . '%');
$sheet->getStyleByColumnAndRow($percentCellIndex, $dataRow)->getNumberFormat()->setFormatCode('0.0%');
// Output 95.6% and formatted as number in Excel
As #ariefbayu said,
$worksheet_details->setCellValue("D14", "=ROUND(SUM((F33 / F34)); 2)");
should work, but to me it threw the error:
PHP Fatal error: Uncaught PHPExcel_Calculation_Exception
so i changed the ; for a ,.
result:
$worksheet_details->setCellValue("D14", "=ROUND(SUM((F33 / F34)), 2)");
You can set the format of your cell to automatically round value to whole number.
$activeSheet->getStyle("A1")->getNumberFormat()->setFormatCode('##');
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 have two tables in a database. Each have a column (varchar255) with a small number (0-30). I'm only trying to divide those two and this is the result:
If one column has the number 6,575 and the other 1,291 the equation should be 5,09. It outputs 6. Other/most results outputs INF
The numbers come from a foreach loop from the database and this is the code from the picture:
echo $row["ton"]." - ".$row_w["weight"]." - ".$row["ton"] / $row_w["weight"]."<br>";
I have tried bcdiv and that outputs nothing and is_infinite = 1. What am I missing?
You need to convert the values (char strings) to float using floatval before doing the division.
The inf means that the result is infinite because you are dividing by 0 or a very small number as a result of an unexpected value coming from dealing with chars as floats, as the program is not able to understand the decimals in a proper way.
Example:
$var = '578.23';
$float_value_of_var = floatval($var);
and your code could be something like this (only as an indication):
echo $row["ton"]." - ".$row_w["weight"]." - ".floatval($row["ton"]) / floatval($row_w["weight"])."<br>";
Thanks #aynber/#Ash-b for seeing my badly stored values.
$a = str_replace(",", ".", $row["ton"]);
$b = str_replace("," ,".", $row_w["weight"]);
echo $row["ton"]." - ".$row_w["weight"]." - ".$a / $b."<br>";
. instead of ,
Can't set a comment to answer, but case solved.
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 need to multiply this POST variable by 12. As an example, if the amount was 10, the result should say:
Amount: 120
Here's my code so far:
Amount :'.$_POST['my_amount'].'<br/>
I tried to run the calculation in another variable, but this doesn't seem to work:
$result = ($_POST['my_amount'])*12;
or maybe it works and my output code is not working:
$vl_text='';
Amount :'.$_POST['my_amount'].'<br/>'.;
If you want your output to resemble your first example.,.. Amount:120 your missing chunks in each of the following 3 examples. first ensure that your $_POST variable is a valid one and set it to a new variable so you can print out the variable if you need to ...
// if you only expect $_POST['my_amount'] to contain integers...
if(is_int(intval($_POST['my_amount']))){
$my_amount = intval($_POST['my_amount']) * 12;
// or if you expect $_POST['my_amount'] to possibly contain a decimal
if(is_float(floatval($_POST['my_amount']))){
$my_amount = floatval($_POST['my_amount']) * 12;
intval ensures that a variable is cast as an integer if it can be, while not entirely necessary as multiplying in php will do this...its good practice to check any variables that you are using for and math functionality.
floatval does the same for for numbers with decimal. as an integer has to be a whole number if your variable could numbers that could contain decimals... use floatval
all of your examples then need to specify to print/echo the string....so
// your second line
echo 'Amount :'.$my_amount .'<br/>';
// your fourth line...
$vl_text='Amount: '.$my_amount;
echo $vl_text;
}
The most logical explanation is that you get string from POST. A good way to achieve what you want is to convert the POST value to int but keep in mind that it could not be numerical.
$int = (is_numeric($_POST['my_amount']) ? (int)$_POST['my_amount'] : 0); //If POST value is numeric then convert to int. If it's not numeric then convert it to 0
$_POST['my_amount'] = 150;
$data = $_POST['my_amount'] * 12;
echo $data;
Result will be 1800
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);