我正在尝试从数据库中读取一个数字并将其写入excel文件,但是我无法保持前导和尾随零。当我检查它时,我能够看到在读取数据时,PHP将其视为数字而不是字符串。我尝试使用空字符串进行类型转换和串联。但是,以下代码
<?php
$a = (string) 180961.65000;
echo $a;
?>
得到以下输出
180961.65
我如何保留零?
答案 0 :(得分:1)
你可以试试这个。
$number = 180961.65000;
$string = sprintf("%f",$number);
echo $string;
//result:180961.650000
答案 1 :(得分:0)
请使用引号将$ a标识为字符串(如果可能,也使用带引号的引号):
$a = "180961.65000";
echo "$a";
答案 2 :(得分:0)
此
需要 number_format $a = "180961.650000000";
$total_len = strlen($a);
$dec_pos = strpos($a, ".");
$diff = $total_len - ($dec_pos +1);
$a = number_format($a,$diff);
$a = str_replace(",", "", $a);
echo $a;
答案 3 :(得分:0)
尝试放
select * from table where Contact Is Not null
答案 4 :(得分:0)
在处理变量时,数据类型会以某种不清楚的方式自动更改。
因此,我建议在变量仍为字符串时明确保留前导和尾随数字。然后在变量变为数字时添加它们。它可能看起来很丑,但对于任意数量的零都是灵活的。
像这样:
// Example number, assume it was received by database
$input = "00018096.16500000";
// Get the leading and trailing zeros as string.
preg_match("/^0+/", $input, $leading);
preg_match("/0+$/", $input, $trailing);
// Mark if there is a decimal point.
$hasDigit = strpos($input, ".") !== false;
// Only for here: force the input to become a number, thus removing all trailing and leading zeros.
$input = 1 * $input;
// Now add the leading and trailing zeroes again and turn the variable back to a string.
$saveOutput = $input . "";
if (count($leading) > 0) {
$saveOutput = $leading[0] . $saveOutput;
}
// If the number is not a float with decimal point, don't add the trailing zeros as they are still there in the integer number.
if (count($trailing) > 0 && $hasDigit) {
$saveOutput = $saveOutput . $trailing[0];
}
// Show result
echo $saveOutput;
// --> Result:
// 00018096.16500000
N.B。,我调用变量saveOutput
,因为你确定它是一个字符串,它不会改变,就像input
一样。