0
Follow
2
View

# How Do I Round Decimals In PHP? [duplicate]

cyyhao 注册会员
2023-01-25 13:41

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;
// 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;
// result=10.11
``````

To know more

lijian672 注册会员
2023-01-25 13:41

Number without round

``````\$double = '21.188624';
echo intval(\$double) . '.' . substr(end(explode('.', \$double)), 0, 2);
``````
csucncdf 注册会员
2023-01-25 13:41

Here's another solution with strtok and str_pad:

``````\$num = 520.00
strtok(round(\$num, 2), '.') . '.' . str_pad(strtok('.'), 2, '0')
``````
dhn8112 注册会员
2023-01-25 13:41

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

cvin456 注册会员
2023-01-25 13:41
``````\$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.

To remove this, do this:

``````\$number = number_format(\$number, 2, ".", "");
``````
dhl7777 注册会员
2023-01-25 13:41
``````\$number = sprintf('%0.2f', \$numbers); // 520.89898989 -> 520.89
``````

This will give you 2 number after decimal.

hs0911 未验证用户
2023-01-25 13:41

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;

{
}

{
}

``````
cxy6688 注册会员
2023-01-25 13:41

Use the PHP number_format() function.

doufei520 注册会员
2023-01-25 13:41

I make my own.

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

Publish Time
2023-01-25 13:41
Update Time
2023-01-25 13:41