## In PHP, how to print a number with 2 decimals, but

2020-03-26 12:11发布

# 问题:

I have a basic index.php page with some variables that I want to print in several places - here are the variables:

``````<?php
\$firstprice = 1.50;
\$secondprice = 3.50;
\$thirdprice = 20;
?>
``````

My challenge is that later in the document, when I print, I get the prices without the second '0' in the price - this is what happens:

``````<?php print "\$firstprice";?> // returns 1.5 - not 1.50!
``````

SO - I know how to do this with JS, but how is this done in PHP 5+? Basically I want to print the second '0' if there is already a decimal, so if the variable is equal to '3', it stays as '3', but if it's equal to '3.5' it converts to display '3.50' with a second '0', etc.

Here's a JS example - what's the PHP equivalent?

JS:

``````.toFixed(2).replace(/[.,]00\$/, ""))
``````

Many thanks!!

# 回答1:

This is simple and it will also let you tweak the format to taste:

``````\$var = sprintf(\$var == intval(\$var) ? "%d" : "%.2f", \$var);
``````

It will format the variable as an integer (`%d`) if it has no decimals, and with exactly two decimal digits (`%.2f`) if it has a decimal part.

See it in action.

Update: As Archimedix points out, this will result in displaying `3.00` if the input value is in the range `(2.995, 3.005)`. Here's an improved check that fixes this:

``````\$var = sprintf(round(\$var, 2) == intval(\$var) ? "%d" : "%.2f", \$var);
``````

# 回答2:

``````<?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 seperator
\$english_format_number = number_format(\$number, 2, '.', '');
// 1234.57

?>
``````

# 回答3:

You could use

``````   if (is_float(\$var))
{
echo number_format(\$var,2,'.','');
}
else
{
echo \$var;
}
``````

# 回答4:

What about something like this :

``````\$value = 15.2; // The value you want to print

\$has_decimal = \$value != intval(\$value);
if (\$has_decimal) {
echo number_format(\$value, 2);
}
else {
echo \$value;
}
``````

Notes :

• You can use `number_format()` to format value to two decimals
• And if the value is an integer, just display it.

# 回答5:

you can use number_format():

``````echo number_format(\$firstprice, 2, ',', '.');
``````

# 回答6:

Alternatively way to print

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

Ta的文章 更多文章

0条评论