PHP value rounding error

4

I have a problem, after assigning a variable a float value as below, 4.85, after multiplying by 100, 48500 and when I will print out the value of 00000000484.

$variavel = 4.85;
$valor = $variavel * 100;
echo sprintf("%011d",$valor);
    
asked by anonymous 30.06.2014 / 14:02

2 answers

4

If you make a var_dump($valor); the result will be:

  

float (485)

This happens because you are using the function sprintf d and you should use f , because the $valor variable is a float .

d - The argument is treated as an integer , and shown as a signed decimal .

f - The argument is treated as a float , and shown as a floating point (locale) number.

F - The argument is treated as a float , and shown as a floating point number (not used locale). Available since PHP 4.3.10 and PHP 5.0.3.

You can also use the number_format function to pass the variable $valor to integer, once it is as float and keep your code:

$variavel = 4.85;
$valor = $variavel * 100;
$valor = number_format( $valor);
echo sprintf("%011d",$valor);

Sources: Manual sprintf ; answer SOEN

    
30.06.2014 / 14:31
2

There are more specific functions for you to work with rounded numbers in php.

Round values up:

<?php 
    echo ceil(9.3);
    // saída = 10
?>

Round values down:

<?php 
    echo floor(9.6);
    // saída = 9
?>

Auto Rounding:

<?php 
    echo round(9.3);
    // saída = 9
    echo round(9.6);
    // saída = 10
?>

Use the form that best fits your project.

    
30.06.2014 / 16:05