[php] Show a number to two decimal places

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?

This question is related to php formatting numbers rounding number-formatting

The answer is


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's another solution with strtok and str_pad:

$num = 520.00
strtok(round($num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')

$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.


$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

It will return 5.98 without rounding the number.


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

$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89

This will give you 2 number after decimal.


Use the PHP number_format() function.


Try:

$number = 1234545454; 
echo  $english_format_number = number_format($number, 2); 

The output will be:

1,234,545,454.00

Number without round

$double = '21.188624';
echo intval($double) . '.' . substr(end(explode('.', $double)), 0, 2);

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);

http://php.net/manual/en/function.round.php

e.g.

echo round(5.045, 2);    // 5.05

echo round(5.055, 2);    // 5.06

Use the PHP number_format() function.

For example,

$num = 7234545423;
echo number_format($num, 2);

The output will be:

7,234,545,423.00

  • 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));


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


Alternatively,

$padded = sprintf('%0.2f', $unpadded); // 520 -> 520.00

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);

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

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"}

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);


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
?>

Adding to other answers, since number_format() will, by default, add thousands separator.

To remove this, do this:

$number = number_format($number, 2, ".", "");

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r

Examples related to numbers

how to display a javascript var in html body How to label scatterplot points by name? Allow 2 decimal places in <input type="number"> Why does the html input with type "number" allow the letter 'e' to be entered in the field? Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array Input type "number" won't resize C++ - how to find the length of an integer How to Generate a random number of fixed length using JavaScript? How do you check in python whether a string contains only numbers? Turn a single number into single digits Python

Examples related to rounding

How to round a numpy array? How to pad a string with leading zeros in Python 3 Python - round up to the nearest ten How to round a Double to the nearest Int in swift? Using Math.round to round to one decimal place? How to round to 2 decimals with Python? Rounding to 2 decimal places in SQL Rounding to two decimal places in Python 2.7? Round a floating-point number down to the nearest integer? Rounding BigDecimal to *always* have two decimal places

Examples related to number-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format / Suppress Scientific Notation from Python Pandas Aggregation Results Formula to convert date to number tSQL - Conversion from varchar to numeric works for all but integer Convert string to decimal number with 2 decimal places in Java What is ToString("N0") format? format a number with commas and decimals in C# (asp.net MVC3) SSRS custom number format Format telephone and credit card numbers in AngularJS How to format a number 0..9 to display with 2 digits (it's NOT a date)