Calculate values (R $) from the quantity

0

I do not know if the title explains the doubt well, but I'll give you an example:

A product costs 50 cents each. I want customers to select the number of products they want to carry. So far so good.

If I multiply $ 0.50xNumberPar, the result is an integer.

However, if I multiply by an odd number, the result is a broken number.

My code:

 if($mc_quantia == 1) {
     //Se a quantia for 1, o preço será 50 centavos                   
     $item = "R$0,50";
 } else {
     //Se não, pegue a quantia e divida por 2 (Porque cada 50 centavos é meio real, então eu preciso dividir por 2)
     $id_4 = $mc_quantia/2;

     $item = 'R$'.$id_4.',00';
 }

The problem:

If the amount is 3, it will return $ 1.50.

I would like it to go straight back to $ 1.50

Can you help me?

    
asked by anonymous 04.10.2016 / 20:47

2 answers

2

Maybe you do not know yet, but for these calculations there is a type of variable called float , which allows you to work with fractional numbers, without having to do this logic with the integer.

Try this:

 if($mc_quantia == 1) {
     $item = "R$0,50";
 } else {
     $id_4 = $mc_quantia*0.5;
     $item = 'R$'.number_format($id_4, 2, ',', '.');
 }

This code above would solve your problem, below is ideal, since the result is the same:

//O if/else é totalmente desnecessário, visto que mesmo sendo a quantidade 1,
//irá retornar o valor calculado corretamente
$id_4 = $mc_quantia*0.5;
$item = 'R$'.number_format($id_4, 2, ',', '.');

OBS. According to official documentation, this function accepts only 1, 2 or 4 parameters, not 3

    
04.10.2016 / 20:54
1

You can simplify the code a bit more:

$valor_unidade = 0.50;

$item = "R$" . number_format($valor_unidade * $mc_quantia);

And as with the number_format documentation, you can format the variable as you like:

<?php

$number = 1234.56;

// Notação Inglesa (padrão)
$english_format_number = number_format($number);
// 1,234

// Notação Francesa
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56

$number = 1234.5678;

// Notação Inglesa com separador de milhar
$english_format_number = number_format($number, 2, '.', '');
// 1234.57

?>
    
04.10.2016 / 20:56