在PHP中,如何打印带有2个小数的数字,但是仅当已经有小数时才打印? [英] In PHP, how to print a number with 2 decimals, but only if there are decimals already?
问题描述
我有一个基本的index.php页面,其中包含一些要在多个位置打印的变量-这是变量:
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;
?>
我的挑战是,在文档的后面,当我打印时,我得到的价格没有第二个价格中的0'-会发生这种情况:
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-我知道如何使用JS,但是如何在PHP 5+中完成呢?基本上,我想打印第二个 0(如果已经有一个小数),因此如果变量等于 3,则保持为 3,但是如果等于 3.5,它将转换为显示 3.50加上第二个 0,等等。
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.
这是一个JS示例-PHP等效项是什么?
Here's a JS example - what's the PHP equivalent?
JS :
.toFixed(2).replace(/[.,]00$/, ""))
非常感谢!
推荐答案
这很简单,它还可以让您调整格式以尝尝:
This is simple and it will also let you tweak the format to taste:
$var = sprintf($var == intval($var) ? "%d" : "%.2f", $var);
它将变量格式化为整数(%d
)(如果没有小数部分),并且只有两位小数(%。2f
)(如果有小数部分)。
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.
更新:正如Archimedix所指出的,如果输入值在(2.995,3.005)范围内,这将导致显示
。这是一种改进的检查,可以解决此问题: 3.00
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);
这篇关于在PHP中,如何打印带有2个小数的数字,但是仅当已经有小数时才打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!