Truncate Value to two decimal places in PHP

Asked

Viewed 1,033 times

-1

I would like to truncate a value into two decimal places in php, without rounding the value. Ex: 25,98/4 = 6,495. But in PHP it appears 6.5 I’m using the number_format:

 $valor_pedido = number_format($pedidoArray['valor_produto'] / ($totalComandasDiv + 1),2, '.', ''); 

How do I get the value 6,49 ?

1 answer

1

You can do it like this:

$numero_decimal = 6.495;
$valor_pedido = floor($numero_decimal * 100) / 100;

The value will be multiplied by 100 and made whole, making the two decimal places part of the whole. Then it is divided by 100 again to turn the last two digits to the decimal places.

In your code it would be

$numero_decimal = $pedidoArray['valor_produto'] / ($totalComandasDiv + 1);
$valor_pedido = floor($numero_decimal * 100) / 100;

Demonstration: https://ideone.com/YSDlKR

  • The result was 6.48.. However the division gives 6.495, it rounded down, as keep only the 6.49 without arrendondar the value?

  • 1

    What are the values of your variables in the case you gave 6.48? Look at an example working https://ideone.com/YSDlKR

Browser other questions tagged

You are not signed in. Login or sign up in order to post.