Question

I am using sprintf function for formatting values. When i say values means both integer and decimal values.But when i use this function it rounds if decimal values are formatted(Not always).Can anyone say the reason behind this.I am using the following code.

echo sprintf("%010d",(1142.87 * 100))."\n"; //displays wrong value
echo str_pad((1142.87 * 100), 10, '0', STR_PAD_LEFT); //displays correct value

What is my need is to format a number into 10 digits.The second one works fine for me.

Was it helpful?

Solution

The rounding is probably happening in the conversion to a float. Instead of d you can use the parameter s which treats the input as a string, and the number will print correctly:

echo sprintf("%010d",(1142.87 * 100))."\n"; //displays wrong value
echo sprintf("%010s",(1142.87 * 100))."\n"; //displays correct value
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top