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.
Related
I am trying to run this code to give me the percentage of two whole numbers.
The code gives me the correct percentage, but does not round the result to a whole number.
For example: 84.33333 to 85.
I am new to PHP and have been unable to create the right code to round up or down for that matter, I have tried floor and ceil.
($result['sales']) / ($result['appointments']) *100, round(0.05)
Any help to point me in the right direction would be appreciated.
If you want to round your fractions up then use ceil function.
Eg:
<?php
echo ceil(4.3); // 5
echo ceil(9.999); // 10
echo ceil(-3.14); // -3
?>
If you want to round your number to some pre-defined fractions then use round function.
round function have a second parameter called precision which can be used for this purpose.
Eg:
<?php
var_dump(round(3.4)); // float(3)
var_dump(round(3.5)); // float(4)
var_dump(round(3.6)); // float(4)
var_dump(round(3.6, 0)); // float(4)
var_dump(round(1.95583, 2)); // float(1.96)
var_dump(round(1241757, -3)); // float(1242000)
var_dump(round(5.045, 2)); // float(5.05)
var_dump(round(5.055, 2)); // float(5.06)
?>
You will get more information from the PHP Docs. Links below.
PHP Ceil Function
PHP Round Function
For your specific case it will be like below:
$percentage = ( $result['sales'] * 100 ) / $result['appointments'];
$percentage_rounded = ceil($percentage);
var_dump($percentage_rounded); exit;
the function you're looking for is ceil(84.3333)
see here
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);
I want to format some numbers from my analytics into currency using the GB money format but as its for a dashboard and doesn't need to be that precise so I want to remove the pence (numbers after the decimal place) and round it which helps with the css layout, how do I do this? Rounding up or down to the nearest pound would be fine.
My code is as follows:
//set locale for currency
setlocale(LC_MONETARY, 'en_GB');
$sales = '8932.83';
echo utf8_encode(money_format('%n', $sales));
This outputs: £8,932.83
However how do I round this to be output as just £8,932 without anything after the decimal place.
I want to use currency format as sometimes the figure is negative in which case money_format returns the number like -£8,932.83 which is preferable to £-8,932 (pound and negative symbol around the wrong way) which is what happened when I formatted using number_format like so:
echo '£'.number_format($sales, 0, '', ',');
Do you want to round it or get rid of the decimals?
To round it which would be 8933 would be:
echo utf8_encode(money_format('%.0n', $sales));
To get rid of the decimals, you could use floor (which rounds down):
echo utf8_encode(money_format('%.0n', floor($sales)));
As the money_format() has been deprecated in PHP 7.4 and removed in PHP 8.0, the suggested function for formatting currency is now NumberFormatter::CURRENCY.
Solving this problem for example would be done this way:
$sales = 8932.83;
$sales = (int)$sales;
$numFormat = new NumberFormatter("en_GB", NumberFormatter::CURRENCY);
$sales = $numFormat->formatCurrency($sales, "EUR");
$sales = str_replace('.00', '', $sales);
echo $sales;
I have a doubt with how to use the number_format and round function together, this because I have an script to import all my supplier's products, but I need round the prices, for example:
Supplier's price: $1854.81
The price rounded: $1854.99 (This is the format that I want)
The price that my script print: $1,854.90
I tryed 3 PHP variant to do this:
Variant #1:
$preciosinr = 1854.81;
echo number_format(round($preciosinr*4)/4,2); //Print 1,854.90
Variant #2
$preciosinr = 1854.81;
$pos = 3 - floor(log10($preciosinr));
echo number_format(round($preciosinr,$pos)-0.10,2); //Print 1,854.75
Variant #3
$preciosinr = 1854.81;
number_format($preciosinr,2);
number_format(round($preciosinr,1),2);
number_format(round($preciosinr,0),2);
echo number_format(round($preciosinr,0)-0.01,2); //Print 1,854.99
As you can see all the variants prints the price with "," and I need the price without this because my system detect the price incorrectly.
I read in php.net that I need use the following sintaxis but I don't know how can integrate with my code.
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
Can you help me?
$price=number_format(round($preciosinr,0)-0.01,2,'.','');
echo $price;
This should work
I found it strange that the answer that was accepted is actually wrong.
Example case:
// The input we want to check
$stringNumber = '7616.95';
// As suggested by accepted answer
$formatted = number_format(round($stringNumber,0)-0.01,2,'.','' );
echo $formatted; // Outputs: 7616.99
A better solution is found here:
https://stackoverflow.com/a/7459107
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('##');