How do I concatenate a decimal value?

-1

Well I have the following code:

<?php
    $numero = "5";
    $decimal = "30";   
?>

What I want to do is concatenate the number, so that the final result is 5.3 and so that the zeros on the right do not contain ...

How can I do this?

    
asked by anonymous 09.11.2018 / 17:28

2 answers

7

What you can do is transform $numero and $decimal into a value accepted by the floatval() .

To do this, just concatenate $numero , one point and $decimal .

Example:

<?php
$numero = "5";
$decimal = "30";
echo floatval("$numero.$decimal");  // floatval("5.30")

Remembering that my solution expects $numero and $decimal to contain only numeric characters.

    
09.11.2018 / 17:37
5

What you want is not to concatenate, it's the opposite, it's transforming texts into numbers with a specific criterion and summing those numbers together. The most common is to use a cast to do this conversion, but nothing guarantees that it will work and you may have problems.

Note that creating the decimal part of the number is your problem, only your code can indicate that this is what you want, so I divided by 100.0 (you can not only divide by 100 because there is an integer value). I preferred to convert to int because there are clues that the number to be used can not already be decimal. If you have the concatenation done before and after converting additional plus one level of possibility of error.

Unbelievably PHP does not have a ready function that generates error if the conversion fails (unless I'm well-off in PHP), so to make sure it works you'll have to do a parser at hand. Without doing this you can not trust the value because it will generate the value 0 without indicating anything that gave error. I imagine you can not trust the number, so you have to validate it. If you can trust, I do not know if you need to do this. I put in the example above how the error can get beaten.

I'm not sure if it's reliable, but is_numeric() function can be the solution .

$numero = "5";
$decimal = "30";
echo (int)$numero + ((int)$decimal / 100.0);
echo "\n";
if (is_numeric($numero) && is_numeric($decimal)) echo (int)$numero + ((int)$decimal / 100.0);
else echo "melhor não calcular, tem erro aí";
$decimal = "a30";
echo "\n";
echo (int)$numero + ((int)$decimal / 100.0);
echo "\n";
if (is_numeric($numero) && is_numeric($decimal)) (int)$numero + ((int)$decimal / 100.0);
else echo "melhor não calcular, tem erro aí";

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

The parentheses in the second expression are more to make clear, they are not needed. If you prefer you can use the intval() function.

I did not merit that this can be a monetary value and this can be another problem. More out of curiosity if it does not read What is the correct way to use float, double, and decimal types?

    
09.11.2018 / 17:36