skip to Main Content

I am working with a Laravel controller where I am restricting the number of decimal places to 2. Here is an example:

$number = 123.456789; // Example number

// Format the number to 2 decimal places
$formatted_number = number_format($number, 2, '.', '');

// Cast the formatted number to a float
$float_number = (float) $formatted_number;

echo $float_number;

When I send the response as JSON and test the API call via Postman, it still displays as 123.456789. However, when I do a dump in the controller, it displays 123.45.

I am unsure why it displays as 123.456789 in Postman.

2

Answers


  1. When you use number_format(), it returns a string. If you want to keep the number as a float and limit the decimal places, use the round() function instead of number_format().

    $number = 123.456789; // Example number
    
    // Round the number to 2 decimal places
    $rounded_number = round($number, 2);
    
    echo $rounded_number;
    

    When you send the response as JSON and test the API call via Postman, it should display as 123.45, and it will be a number, not a string.

    Login or Signup to reply.
  2. If you need to get the same value in Postman, you need to keep the formatted value as a string.

    $number = 123.456789;
    $formatted_number = number_format($number, 2, '.', ''); 
    return response()->json(['number' => $formatted_number]);
    
    

    The reason why you are having this:

    the number_format() helper function formats the number to two decimal places and then converts the float to a string representation as per the docs (https://www.php.net/manual/en/function.number-format.php), which is why you get "123.45". but from the sample code provided, you are casting the string back to a float which is converted to a floating-point number with two decimal places.
    Floating-point precision can lead to unexpected results when the number is serialized again (such as converting to JSON).Since you are checking from Postman, JSON encoding in PHP uses the IEEE 754 double precision format, which can introduce precision issues. This is the reason why your $float_number displays more decimal places than expected when encoded into JSON for postman

    this might be helpful
    PHP – Floating Number Precision

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search