4
I have a problem, after assigning to a variable a float value as below, 4.85, after multiplying by 100, 48500 and when I print out the value of 00000000484.
$variavel = 4.85;
$valor = $variavel * 100;
echo sprintf("%011d",$valor);
4
I have a problem, after assigning to a variable a float value as below, 4.85, after multiplying by 100, 48500 and when I print out the value of 00000000484.
$variavel = 4.85;
$valor = $variavel * 100;
echo sprintf("%011d",$valor);
4
If you make a var_dump($valor);
the result will be :
float(485)
This is because you are using in the function sprintf
the d and you should use f, because the variable $valor
is a float.
d - The argument is treated as a whole, and shown as a decimal number down-low.
f - The argument is treated as a float, and shown as a floating point number (from the locale).
F - the argument is treated as a float, and shown as a floating point number (locale not used). Available since PHP 4.3.10 and PHP 5.0.3.
You can also use the function number_format
to pass the variable $valor
for whole, once this meets as float and keep your code:
$variavel = 4.85;
$valor = $variavel * 100;
$valor = number_format( $valor);
echo sprintf("%011d",$valor);
Sources: Manual sprintf; reply SOEN
2
There are more specific functions for you to work with rounded php numbers.
Round up values:
<?php
echo ceil(9.3);
// saída = 10
?>
Round down values:
<?php
echo floor(9.6);
// saída = 9
?>
Automatic rounding:
<?php
echo round(9.3);
// saída = 9
echo round(9.6);
// saída = 10
?>
Use the shape that best fits your project.
Browser other questions tagged php float int
You are not signed in. Login or sign up in order to post.
But look at the following situation, I’m turning a float into an int, since it multiplies 4.85 by 100 and so becomes 48500, if he only takes the whole part would take the value of 48500.00 ? Really this way I managed to solve the problem but this doubt was in the head...,
– Marco André
If you make a
var_dump($valor);
the result will befloat(485)
. So you have to turn first into an integer.– Jorge B.
You can also use the
$valor = number_format( $valor);
and keep your code. to format to whole.– Jorge B.
@Marcoandré Updated response.
– Jorge B.
Thanks @Jorge B. already changed my code I’m using sprintf("%011.0f",$value);, is for an archive layout for integration, thanks for the help and attention !!
– Marco André