Related
I am extremely new to PHP, and I am having some issues with the number_format() function.
I am performing a calculation which is, correctly, returning this result: 6215.
However, I want this value to be displayed/echoed as 62.15. I have played around with the number_format() function to no avail.
Any help would be greatly appreciated!
You have 2 potential tasks here.
1.) You want to change your number (divide by 100)
<?php
$number = 6215;
$number = $number / 100;
echo $number;
?>
Renders as 62.15
2.) You may want additional formatting to make a "pretty" number
From the docs: https://www.php.net/manual/en/function.number-format.php
// Function signature syntax
number_format(
float $num,
int $decimals = 0,
?string $decimal_separator = ".",
?string $thousands_separator = ","
)
<?php
$number = 1006215.56;
$pretty_number = number_format($number, 2, '.', '');
echo $pretty_number;
?>
Renders as 1,006,215.56
This was directly pulled from the php.net documentation, which I think is really great.
https://www.php.net/manual/en/function.number-format.php
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
What's the correct way to round a PHP string to two decimal places?
$number = "520"; // It's a string from a database
$formatted_number = round_to_2dp($number);
echo $formatted_number;
The output should be 520.00;
How should the round_to_2dp() function definition be?
You can use number_format():
return number_format((float)$number, 2, '.', '');
Example:
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
This function returns a string.
Use round() (use if you are expecting a number in float format only, else use number_format() as an answer given by Codemwnci):
echo round(520.34345, 2); // 520.34
echo round(520.3, 2); // 520.3
echo round(520, 2); // 520
From the manual:
Description:
float round(float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]]);
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
...
Example #1 round() examples
<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>
Example #2 mode examples
<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP); // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9
echo round(8.5, 0, PHP_ROUND_HALF_UP); // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD); // 9
?>
Alternatively,
$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00
http://php.net/manual/en/function.round.php
e.g.
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
Try:
$number = 1234545454;
echo $english_format_number = number_format($number, 2);
The output will be:
1,234,545,454.00
Use the PHP number_format() function.
For example,
$num = 7234545423;
echo number_format($num, 2);
The output will be:
7,234,545,423.00
You can use the PHP printf or sprintf functions:
Example with sprintf:
$num = 2.12;
echo sprintf("%.3f", $num);
You can run the same without echo as well. Example: sprintf("%.3f", $num);
Output:
2.120
Alternatively, with printf:
echo printf("%.2f", $num);
Output:
2.124
Another more exotic way to solve this issue is to use bcadd() with a dummy value for the $right_operand of 0.
$formatted_number = bcadd($number, 0, 2);
use round(yourValue,decimalPoint) (php manual’s page) or number_format(yourValue,decimalPoint);
number_format() return value as string like this type 1,234.67. so in this case you can not use it for addition or any calculation. if you try then you have to deal with Number Format Error...
In this case round(121222.299000000,2) will be better option.
The result would be 121222.29 ...
bcdiv($number, 1, 2) // 2 varies for digits after the decimal point
This will display exactly two digits after the decimal point.
Advantage:
If you want to display two digits after a float value only and not for int, then use this.
Here I get two decimals after the . (dot) using a function...
function truncate_number($number, $precision = 2) {
// Zero causes issues, and no need to truncate
if (0 == (int)$number) {
return $number;
}
// Are we negative?
$negative = $number / abs($number);
// Cast the number to a positive to solve rounding
$number = abs($number);
// Calculate precision number for dividing / multiplying
$precision = pow(10, $precision);
// Run the math, re-applying the negative value to ensure
// returns correctly negative / positive
return floor( $number * $precision ) / $precision * $negative;
}
Results from the above function:
echo truncate_number(2.56789, 1); // 2.5
echo truncate_number(2.56789); // 2.56
echo truncate_number(2.56789, 3); // 2.567
echo truncate_number(-2.56789, 1); // -2.5
echo truncate_number(-2.56789); // -2.56
echo truncate_number(-2.56789, 3); // -2.567
New Correct Answer
Use the PHP native function bcdiv
echo bcdiv(2.56789, 1, 1); // 2.5
echo bcdiv(2.56789, 1, 2); // 2.56
echo bcdiv(2.56789, 1, 3); // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 2); // -2.56
echo bcdiv(-2.56789, 1, 3); // -2.567
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', '');
It will return 5.98 without rounding the number.
Use the PHP number_format() function.
For conditional rounding off ie. show decimal where it's really needed otherwise whole number
123.56 => 12.56
123.00 => 123
$somenumber = 123.56;
$somenumber = round($somenumber,2);
if($somenumber == intval($somenumber))
{
$somenumber = intval($somenumber);
}
echo $somenumber; // 123.56
$somenumber = 123.00;
$somenumber = round($somenumber,2);
if($somenumber == intval($somenumber))
{
$somenumber = intval($somenumber);
}
echo $somenumber; // 123
I make my own.
$decimals = 2;
$number = 221.12345;
$number = $number * pow(10, $decimals);
$number = intval($number);
$number = $number / pow(10, $decimals);
round_to_2dp is a user-defined function, and nothing can be done unless you posted the declaration of that function.
However, my guess is doing this: number_format($number, 2);
$twoDecNum = sprintf('%0.2f', round($number, 2));
The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.
Adding to other answers, since number_format() will, by default, add thousands separator.
To remove this, do this:
$number = number_format($number, 2, ".", "");
$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89
This will give you 2 number after decimal.
If you want to use two decimal digits in your entire project, you can define:
bcscale(2);
Then the following function will produce your desired result:
$myvalue = 10.165445;
echo bcadd(0, $myvalue);
// result=10.11
But if you don't use the bcscale function, you need to write the code as follows to get your desired result.
$myvalue = 10.165445;
echo bcadd(0, $myvalue, 2);
// result=10.11
To know more
BC Math Functions
bcscale
Number without round
$double = '21.188624';
echo intval($double) . '.' . substr(end(explode('.', $double)), 0, 2);
Here's another solution with strtok and str_pad:
$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')
Choose the number of decimals
Format commas(,)
An option to trim trailing zeros
Once and for all!
function format_number($number,$dec=0,$trim=false){
if($trim){
$parts = explode(".",(round($number,$dec) * 1));
$dec = isset($parts[1]) ? strlen($parts[1]) : 0;
}
$formatted = number_format($number,$dec);
return $formatted;
}
Examples
echo format_number(1234.5,2,true); //returns 1,234.5
echo format_number(1234.5,2); //returns 1,234.50
echo format_number(1234.5); //returns 1,235
That's the same question I came across today and want to round a number and return float value up to a given decimal place and it must not be string (as returned from number_format)
the answer is
echo sprintf('%.' . $decimalPlaces . 'f', round($number, $decimalPlaces));
In case you use math equation like I did you can set it like this:
{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"}
What's the correct way to round a PHP string to two decimal places?
$number = "520"; // It's a string from a database
$formatted_number = round_to_2dp($number);
echo $formatted_number;
The output should be 520.00;
How should the round_to_2dp() function definition be?
You can use number_format():
return number_format((float)$number, 2, '.', '');
Example:
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
This function returns a string.
Use round() (use if you are expecting a number in float format only, else use number_format() as an answer given by Codemwnci):
echo round(520.34345, 2); // 520.34
echo round(520.3, 2); // 520.3
echo round(520, 2); // 520
From the manual:
Description:
float round(float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]]);
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
...
Example #1 round() examples
<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>
Example #2 mode examples
<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP); // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9
echo round(8.5, 0, PHP_ROUND_HALF_UP); // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD); // 9
?>
Alternatively,
$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00
http://php.net/manual/en/function.round.php
e.g.
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
Try:
$number = 1234545454;
echo $english_format_number = number_format($number, 2);
The output will be:
1,234,545,454.00
Use the PHP number_format() function.
For example,
$num = 7234545423;
echo number_format($num, 2);
The output will be:
7,234,545,423.00
You can use the PHP printf or sprintf functions:
Example with sprintf:
$num = 2.12;
echo sprintf("%.3f", $num);
You can run the same without echo as well. Example: sprintf("%.3f", $num);
Output:
2.120
Alternatively, with printf:
echo printf("%.2f", $num);
Output:
2.124
Another more exotic way to solve this issue is to use bcadd() with a dummy value for the $right_operand of 0.
$formatted_number = bcadd($number, 0, 2);
use round(yourValue,decimalPoint) (php manual’s page) or number_format(yourValue,decimalPoint);
number_format() return value as string like this type 1,234.67. so in this case you can not use it for addition or any calculation. if you try then you have to deal with Number Format Error...
In this case round(121222.299000000,2) will be better option.
The result would be 121222.29 ...
bcdiv($number, 1, 2) // 2 varies for digits after the decimal point
This will display exactly two digits after the decimal point.
Advantage:
If you want to display two digits after a float value only and not for int, then use this.
Here I get two decimals after the . (dot) using a function...
function truncate_number($number, $precision = 2) {
// Zero causes issues, and no need to truncate
if (0 == (int)$number) {
return $number;
}
// Are we negative?
$negative = $number / abs($number);
// Cast the number to a positive to solve rounding
$number = abs($number);
// Calculate precision number for dividing / multiplying
$precision = pow(10, $precision);
// Run the math, re-applying the negative value to ensure
// returns correctly negative / positive
return floor( $number * $precision ) / $precision * $negative;
}
Results from the above function:
echo truncate_number(2.56789, 1); // 2.5
echo truncate_number(2.56789); // 2.56
echo truncate_number(2.56789, 3); // 2.567
echo truncate_number(-2.56789, 1); // -2.5
echo truncate_number(-2.56789); // -2.56
echo truncate_number(-2.56789, 3); // -2.567
New Correct Answer
Use the PHP native function bcdiv
echo bcdiv(2.56789, 1, 1); // 2.5
echo bcdiv(2.56789, 1, 2); // 2.56
echo bcdiv(2.56789, 1, 3); // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 2); // -2.56
echo bcdiv(-2.56789, 1, 3); // -2.567
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', '');
It will return 5.98 without rounding the number.
Use the PHP number_format() function.
For conditional rounding off ie. show decimal where it's really needed otherwise whole number
123.56 => 12.56
123.00 => 123
$somenumber = 123.56;
$somenumber = round($somenumber,2);
if($somenumber == intval($somenumber))
{
$somenumber = intval($somenumber);
}
echo $somenumber; // 123.56
$somenumber = 123.00;
$somenumber = round($somenumber,2);
if($somenumber == intval($somenumber))
{
$somenumber = intval($somenumber);
}
echo $somenumber; // 123
I make my own.
$decimals = 2;
$number = 221.12345;
$number = $number * pow(10, $decimals);
$number = intval($number);
$number = $number / pow(10, $decimals);
round_to_2dp is a user-defined function, and nothing can be done unless you posted the declaration of that function.
However, my guess is doing this: number_format($number, 2);
$twoDecNum = sprintf('%0.2f', round($number, 2));
The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.
Adding to other answers, since number_format() will, by default, add thousands separator.
To remove this, do this:
$number = number_format($number, 2, ".", "");
$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89
This will give you 2 number after decimal.
If you want to use two decimal digits in your entire project, you can define:
bcscale(2);
Then the following function will produce your desired result:
$myvalue = 10.165445;
echo bcadd(0, $myvalue);
// result=10.11
But if you don't use the bcscale function, you need to write the code as follows to get your desired result.
$myvalue = 10.165445;
echo bcadd(0, $myvalue, 2);
// result=10.11
To know more
BC Math Functions
bcscale
Number without round
$double = '21.188624';
echo intval($double) . '.' . substr(end(explode('.', $double)), 0, 2);
Here's another solution with strtok and str_pad:
$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')
Choose the number of decimals
Format commas(,)
An option to trim trailing zeros
Once and for all!
function format_number($number,$dec=0,$trim=false){
if($trim){
$parts = explode(".",(round($number,$dec) * 1));
$dec = isset($parts[1]) ? strlen($parts[1]) : 0;
}
$formatted = number_format($number,$dec);
return $formatted;
}
Examples
echo format_number(1234.5,2,true); //returns 1,234.5
echo format_number(1234.5,2); //returns 1,234.50
echo format_number(1234.5); //returns 1,235
That's the same question I came across today and want to round a number and return float value up to a given decimal place and it must not be string (as returned from number_format)
the answer is
echo sprintf('%.' . $decimalPlaces . 'f', round($number, $decimalPlaces));
In case you use math equation like I did you can set it like this:
{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"}
I have a price "0,10" or "00000,10"
Now when i try
number_format($price, 2, ',', '')
I get 0,00.
How can i fix this? I want 0,10 $.
I don't want rounding.
Or when i have 5,678, i get 5,68. But i want 5,67.
Several people have mentioned rounding it to 3 and then dropping the last character. This actually does not work. Say you have 2.9999 and round it to 3 it's 3.000.
This is still not accurate, the best solution is this:
$price = '5.678';
$dec = 2;
$price = number_format(floor($price*pow(10,$dec))/pow(10,$dec),$dec);
What this does is takes the price and multiplies it by 100 (10^decimal) which gives 567.8, then we use floor to get it to 567, and then we divide it back by 100 to get 5.67
You can increase the size of the number before rounding down with floor:
$price = floor($price * 100) / 100;
$formatted = number_format($price, 2, ',', '');
Another solution, which may give better precision since it avoids floating-point arithmetic, is to format it with three decimals and throw away the last digit after formatting:
$formatted = substr(number_format($price, 3, ',', ''), 0, -1);
you should convert comma-filled number back to normal decimal before with str_replace.
$number = str_replace(",", ".", $number);
and then you can use number_format
"00000,10" is a string. You should a decimal point. To get the desired behaviour, you could use:
echo substr(number_format(str_replace(',', '.', $price), 3, ',', ''), 0, -1);
Use this (needs activated intl PHP extension)
$numberFmtCurrency = new NumberFormatter('de_AT', NumberFormatter::CURRENCY);
$numberFmtCurrency->setAttribute(NumberFormatter::ROUNDING_INCREMENT, 0);
$numberFmtCurrency->formatCurrency(328.13, 'EUR'); // prints € 328.13 (and not 328.15)
If you are literally just wanting to clear leading zeroes and just limit the length, rather than round to a certain amount of decimal places, a more generalised solution could be this function:
function cutafter($string,$cutpoint,$length)
{
$temp = explode($cutpoint,$string);
$int = $temp[0];
$sub = $temp[1];
return number_format($int,0).','.substr($sub,0,$length);
}
Example:
$number = "005,678";
$answer = cutafter($number,",",2);
$answer now equals "5,67"
Just before number_format is executed the string "0,10" is converted by php to an number. because php always uses the engish notation the it won't look after the comma.
echo "4 apples" + 2;
output: 6
The " apples" part is ignored just as your ",10" is ignored.
Converting the "," to a "." allows php to see the other digits.
$price = str_replace(',', '.', '0,10');
number_format($price, 2, ',', '');
My problem was that html validator error messege thar number_format() argument is not double.
I solved this error message by placing floatval for that argument like number_format(floatval($var),2,'.',' ') and that is working good.
function format_numeric($value) {
if (is_numeric($value)) { // is number
if (strstr($value, ".")) { // is decimal
$tmp = explode(".", $value);
$int = empty($tmp[0]) ? '0' : $tmp[0];
$dec = $tmp[1];
$value = number_format($int, 0) . "." . $dec;
return $value;
}
$value = number_format($value);
return $value;
}
return $value; // is string
}
Unit Testing:
Passed / 1100000 => 1,100,000
Passed / ".9987" => .9987
Passed / 1100.22 => 1,100.22
Passed / 0.9987 => 0.9987
Passed / .9987 => 0.9987
Passed / 11 => 11
Passed / 11.1 => 11.1
Passed / 11.1111 => 11.1111
Passed / "abc" => "abc"
See this answer for more details.
function numberFormat($number, $decimals = 0, $decPoint = '.' , $thousandsSep = ',')
{
$negation = ($number < 0) ? (-1) : 1;
$coefficient = pow(10, $decimals);
$number = $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
return number_format($number, $decimals, $decPoint, $thousandsSep);
}
What's the correct way to round a PHP string to two decimal places?
$number = "520"; // It's a string from a database
$formatted_number = round_to_2dp($number);
echo $formatted_number;
The output should be 520.00;
How should the round_to_2dp() function definition be?
You can use number_format():
return number_format((float)$number, 2, '.', '');
Example:
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
This function returns a string.
Use round() (use if you are expecting a number in float format only, else use number_format() as an answer given by Codemwnci):
echo round(520.34345, 2); // 520.34
echo round(520.3, 2); // 520.3
echo round(520, 2); // 520
From the manual:
Description:
float round(float $val [, int $precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]]);
Returns the rounded value of val to specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
...
Example #1 round() examples
<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>
Example #2 mode examples
<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP); // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9
echo round(8.5, 0, PHP_ROUND_HALF_UP); // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD); // 9
?>
Alternatively,
$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00
http://php.net/manual/en/function.round.php
e.g.
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
Try:
$number = 1234545454;
echo $english_format_number = number_format($number, 2);
The output will be:
1,234,545,454.00
Use the PHP number_format() function.
For example,
$num = 7234545423;
echo number_format($num, 2);
The output will be:
7,234,545,423.00
You can use the PHP printf or sprintf functions:
Example with sprintf:
$num = 2.12;
echo sprintf("%.3f", $num);
You can run the same without echo as well. Example: sprintf("%.3f", $num);
Output:
2.120
Alternatively, with printf:
echo printf("%.2f", $num);
Output:
2.124
Another more exotic way to solve this issue is to use bcadd() with a dummy value for the $right_operand of 0.
$formatted_number = bcadd($number, 0, 2);
use round(yourValue,decimalPoint) (php manual’s page) or number_format(yourValue,decimalPoint);
number_format() return value as string like this type 1,234.67. so in this case you can not use it for addition or any calculation. if you try then you have to deal with Number Format Error...
In this case round(121222.299000000,2) will be better option.
The result would be 121222.29 ...
bcdiv($number, 1, 2) // 2 varies for digits after the decimal point
This will display exactly two digits after the decimal point.
Advantage:
If you want to display two digits after a float value only and not for int, then use this.
Here I get two decimals after the . (dot) using a function...
function truncate_number($number, $precision = 2) {
// Zero causes issues, and no need to truncate
if (0 == (int)$number) {
return $number;
}
// Are we negative?
$negative = $number / abs($number);
// Cast the number to a positive to solve rounding
$number = abs($number);
// Calculate precision number for dividing / multiplying
$precision = pow(10, $precision);
// Run the math, re-applying the negative value to ensure
// returns correctly negative / positive
return floor( $number * $precision ) / $precision * $negative;
}
Results from the above function:
echo truncate_number(2.56789, 1); // 2.5
echo truncate_number(2.56789); // 2.56
echo truncate_number(2.56789, 3); // 2.567
echo truncate_number(-2.56789, 1); // -2.5
echo truncate_number(-2.56789); // -2.56
echo truncate_number(-2.56789, 3); // -2.567
New Correct Answer
Use the PHP native function bcdiv
echo bcdiv(2.56789, 1, 1); // 2.5
echo bcdiv(2.56789, 1, 2); // 2.56
echo bcdiv(2.56789, 1, 3); // 2.567
echo bcdiv(-2.56789, 1, 1); // -2.5
echo bcdiv(-2.56789, 1, 2); // -2.56
echo bcdiv(-2.56789, 1, 3); // -2.567
$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', '');
It will return 5.98 without rounding the number.
Use the PHP number_format() function.
For conditional rounding off ie. show decimal where it's really needed otherwise whole number
123.56 => 12.56
123.00 => 123
$somenumber = 123.56;
$somenumber = round($somenumber,2);
if($somenumber == intval($somenumber))
{
$somenumber = intval($somenumber);
}
echo $somenumber; // 123.56
$somenumber = 123.00;
$somenumber = round($somenumber,2);
if($somenumber == intval($somenumber))
{
$somenumber = intval($somenumber);
}
echo $somenumber; // 123
I make my own.
$decimals = 2;
$number = 221.12345;
$number = $number * pow(10, $decimals);
$number = intval($number);
$number = $number / pow(10, $decimals);
round_to_2dp is a user-defined function, and nothing can be done unless you posted the declaration of that function.
However, my guess is doing this: number_format($number, 2);
$twoDecNum = sprintf('%0.2f', round($number, 2));
The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.
Adding to other answers, since number_format() will, by default, add thousands separator.
To remove this, do this:
$number = number_format($number, 2, ".", "");
$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89
This will give you 2 number after decimal.
If you want to use two decimal digits in your entire project, you can define:
bcscale(2);
Then the following function will produce your desired result:
$myvalue = 10.165445;
echo bcadd(0, $myvalue);
// result=10.11
But if you don't use the bcscale function, you need to write the code as follows to get your desired result.
$myvalue = 10.165445;
echo bcadd(0, $myvalue, 2);
// result=10.11
To know more
BC Math Functions
bcscale
Number without round
$double = '21.188624';
echo intval($double) . '.' . substr(end(explode('.', $double)), 0, 2);
Here's another solution with strtok and str_pad:
$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')
Choose the number of decimals
Format commas(,)
An option to trim trailing zeros
Once and for all!
function format_number($number,$dec=0,$trim=false){
if($trim){
$parts = explode(".",(round($number,$dec) * 1));
$dec = isset($parts[1]) ? strlen($parts[1]) : 0;
}
$formatted = number_format($number,$dec);
return $formatted;
}
Examples
echo format_number(1234.5,2,true); //returns 1,234.5
echo format_number(1234.5,2); //returns 1,234.50
echo format_number(1234.5); //returns 1,235
That's the same question I came across today and want to round a number and return float value up to a given decimal place and it must not be string (as returned from number_format)
the answer is
echo sprintf('%.' . $decimalPlaces . 'f', round($number, $decimalPlaces));
In case you use math equation like I did you can set it like this:
{math equation="x + y" x=4.4444 y=5.0000 format="%.2f"}