By Rich Bradshaw


2010-12-19 15:10:30 8 Comments

What's the correct way to round a PHP string to 2 decimal places?

$number = "520"; // It's a string from a DB

$formatted_number = round_to_2dp($number);

echo $formatted_number;

The output should be 520.00;

How should the round_to_2dp() function definition be?

21 comments

@Bryan 2019-03-14 18:59:10

Haven't seen this one yet so, here's another solution with strtok and str_pad:

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

@Viney 2018-06-19 07:03:04

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    

@Sani Kamal 2018-05-21 07:51:20

Use PHP number_format() function. e.g.

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

The output will be:

7,234,545,423.00

@Wasim A. 2016-02-26 11:56:06

bcdiv($number, 1, 2) //2 varies for digits after decimal

This will display exactly two digits after decimal.

Advantage: If you want to display two digits after float value only and not for int then use this.

@Shovas 2018-11-13 15:26:36

This is the most universal solution if you have bcdiv (it's a stock but non-default package on centos6).

@jewelhuq 2017-05-09 21:47:19

If you want to use 2 decimal digit 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 bcscale function you need to write the code as follow to get your desire result

  $myvalue=10.165445;
  echo bcadd(0,$myvalue,2);
 //result=10.11

To know more

@powtac 2017-02-14 17:47:05

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

@ColinM 2018-07-18 20:25:15

Note that bc* functions do not round up, they always round down. For example, bcadd("1.0999","0.0",1) yields "1.0", not "1.1".

@Mr. HK 2017-01-21 03:48:40

Here I getting 2 decimal after .(dot) using 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

@Aditya P Bhatt 2015-03-09 08:22:49

You can use php printf or sprintf functions:

example with sprintf:

$num = 2.12;
echo sprintf("%.3f",$num);

You can run same without echo as well, ex: sprintf("%.3f",$num);

output:

2.120

Alternatively, with printf:

echo printf("%.2f",$num);

output:

2.124 

@mrphpguru 2015-07-29 03:11:15

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

It will return 5.98 without rounding the number.

@JohnS 2015-11-24 21:14:58

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

@S'copion Sam 2015-09-11 09:39:47

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

This will give you 2 number after decimal.

@Boaz Rymland 2016-03-17 13:25:18

No it won't. I don't know when this post was written but if you try it with your own example, at least on my machine :-) , it will output 520.90. Meaning, Rounding WILL occur. Be careful!

@Abhishek Sharma 2015-04-29 09:55:23

Number without round

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

@Somnath Muluk 2011-12-01 09:11:01

Use round() (use if you are expecting number in float format only, else use number_format() as answer given by Codemwnci ):

echo round(520.34345,2);    // 520.34

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

@Claudiu Creanga 2016-04-14 16:00:24

@khuderm round($number, 2); doesn't work. I want 520.00 not 520. Can't believe round doesn't do that by default.

@Sadikhasan 2013-12-20 11:24:40

You can use PHP round() function.

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

@Mark Amery 2014-03-16 21:27:49

-1; this answer adds nothing new that Somnath Muluk's answer didn't already contain 2 years earlier.

@Mark Amery 2014-03-16 21:39:32

It's also wrong, as noted in my comment on Somnath's answer.

@SystemX17 2010-12-19 15:12:50

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

e.g.

echo round(5.045, 2);    // 5.05

echo round(5.055, 2);    // 5.06

@Shamim Hafiz 2010-12-19 15:15:08

Round will do the exact functionality that Rich is wanting, but number_format() would be more interesting to look into for all kinds of numerical formatting.

@SystemX17 2010-12-19 15:15:35

This method will perform rounding as well over just forcing the digits ".00" on the end.

@Rich Bradshaw 2010-12-19 15:18:25

I'd tried round, but it doesn't work - it won't add the extra .00.

@SystemX17 2010-12-20 02:13:45

Try using one of the examples I have there, it on it's own in a PHP script. You should get the commented result. If not then you have a problem with your PHP setup somewhere.

@user761100 2018-10-15 14:59:23

round(520, 2) returns 520, not 520.00 as required by @Rich

@Codemwnci 2010-12-19 15:14:12

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.

@StringsOnFire 2014-02-26 22:07:33

round() would be better for it's readability and simplicity too, but for anything critical be aware that it has been known to be buggy

@Mark Amery 2014-03-16 21:38:45

@ÁlvaroG.Vicario round doesn't solve the OP's problem here. round("520", 2) returns the float 520, and echoing that will of course not show it to 2 decimal places. For the OP's purpose - showing an integer to 2 decimal places by padding it with trailing zeroes - you need a number formatting function, not a rounding function.

@SPRBRN 2014-05-08 15:06:49

All the other answers are limited to decimal values with a dot notation. When you need to get 520,00 instead of 520.00, this simply works.

@Wasim A. 2016-02-26 11:53:18

if you want to limit only float but not int then bcdiv($number,1,2)

@vdegenne 2017-01-18 22:45:55

I don't think if it's because i am using php 7.1.0 but the float-casting seems useless in my case and adding or removing will have no effect to the end result.

@jewelhuq 2018-05-31 19:21:03

I think you should use bcadd(0,$yournumber,2) it will give you perfect result.

@joanlgr 2013-09-20 10:19:06

I make my own.

$decimals = 2;
$number = 221.12345;
$number = $number * pow(10,$decimals);
$number = intval($number);
$number = $number / pow(10,$decimals);

@Lightbulb1 2013-12-11 14:43:35

Its nice to see some of the maths needed to do this. Although using a built in function is preferred for me. Theres no point re-inventing the wheel.

@joanlgr 2013-12-20 15:16:30

Sorry, but round(), as it says, round de number, and sometimes, i do not want to round.

@Biju 2013-01-11 07:04:38

Try:

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

The output will be:

1,234,545,454.00

@Davіd 2015-02-28 22:39:03

That works, but the output would be a string and not a number.

@Keir Simmons 2015-07-08 23:44:36

Simply prepend a + to number_format.

@Mihai P. 2016-10-31 20:51:56

if you want to use number_format at least make it number_format($number, 2, '.', '')

@Marc B 2010-12-19 15:53:04

Alternatively,

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

@SPRBRN 2014-04-28 13:55:56

So what if you want 520,00? I guess the other answer works better in that case.

@pythonian29033 2014-08-19 12:34:32

^no the other answer will not give two decimal places for an int

@Amb3rL4nn 2017-02-22 05:48:05

other reasons you may want this is you dont want rounding... or in my cause SQL floats returned are not treated the same as normal floats which is a PHP math bug

@ajreal 2010-12-19 15:13:58

round_to_2dp is an user defined function, nothing can be done unless you posted the declaration of that function

However, my guess is doing this number_format($number,2);

@Mark Amery 2013-11-12 16:23:56

From your first paragraph, I think you've misunderstood the question. round_to_2dp($number); was meant as pseudocode; the OP was asking for somebody to tell him what to replace that expression with.

@Shamim Hafiz 2010-12-19 15:13:24

Use PHP number_format() function.

Related Questions

Sponsored Content

65 Answered Questions

[SOLVED] Round to at most 2 decimal places (only if necessary)

27 Answered Questions

[SOLVED] How to convert decimal to hexadecimal in JavaScript

43 Answered Questions

[SOLVED] How to print a number with commas as thousands separators in JavaScript

18 Answered Questions

[SOLVED] Reference — What does this symbol mean in PHP?

27 Answered Questions

[SOLVED] Format number to always show 2 decimal places

23 Answered Questions

[SOLVED] Limiting floats to two decimal points

12 Answered Questions

[SOLVED] Formatting Decimal places in R

  • 2010-08-09 19:57:41
  • Brandon Bertelsen
  • 416067 View
  • 222 Score
  • 12 Answer
  • Tags:   r formatting rounding

48 Answered Questions

[SOLVED] Validate decimal numbers in JavaScript - IsNumeric()

29 Answered Questions

[SOLVED] Formatting a number with exactly two decimals in JavaScript

29 Answered Questions

[SOLVED] How to round a number to n decimal places in Java

Sponsored Content