Fix PHP JSON Float Formatting: Always Show Two Decimal Places Without Converting to String

Working with numeric values in JSON from PHP often causes one frustrating issue. Numbers like 900.00 end up as 900. Sometimes they appear as a string like “900.00“. APIs and integrations that need exact decimal formatting will break on that output.

This guide shows the problem, gives clear explanations, and presents a step-by-step fix. The goal is a numeric JSON value that shows two decimals and remains a number.

The Common Problem: PHP Strips Decimals or Converts to String

Here is a common snippet you might use:

It looks correct at first. The code formats the number to two decimals and casts to float. The actual JSON output often looks like this:

Reason: number_format() returns a string. Casting that string to (float) removes trailing zeros. The result becomes 900.

Step 1: Clean and Convert the Price Safely

Price values often include $, commas, or spaces. Sanitize the input first:

This removes extra characters and converts the result to a float. If you then do this:

The output will display:

The float value loses trailing zeros. PHP stores numeric value only, not formatting.

Step 2: Understand JSON Limitations

JSON treats numbers as numeric values without formatting. Values like 900, 900.0, and 900.00 all represent the same number. If the receiving API requires exactly two decimal places for currency, json_encode() alone will not produce the desired literal text. You need to inject a formatted numeric literal into the final JSON string.

Step 3: Inject a Formatted Numeric Literal into JSON

Use this robust approach:

Output example:

The “price” field is now a numeric literal and shows two decimals. The value is valid JSON and not a string.

Step 4: Why This Works

json_encode() prints floats as plain numbers without formatting. PHP floats do not retain trailing zeros. Manually injecting the text 900.00 into the JSON string produces the exact literal you need. JSON parsers will read 900.00 as a number, not as text.

This method keeps all other fields encoded normally and replaces only the price token with the exact numeric format the API expects.

Bonus: Use JSON_PRESERVE_ZERO_FRACTION (If PHP 5.6+)

PHP offers a flag you can try:

This preserves a zero fraction like 900.0 in the output. It does not guarantee two decimal places like 900.00. Use manual injection when you need exactly two decimals.

Common Pitfalls Developers Run Into

1. Using number_format() directly in $postfields:

    This yields a string. JSON shows “price”: “900.00” instead of a numeric value.

    2. Casting a formatted string back to float:

    This removes trailing zeros and reduces 900.00 to 900.

    3. Relying on floats to preserve decimals.

     PHP floats do not hold formatting. Rounding them still yields a number without fixed decimal digits in JSON.

    4. Skipping input sanitization

    If $postfield[‘total_price’] contains $ or commas, casting directly can give unexpected results. Strip symbols first.

    Deployment Checklist for Clean Float JSON Output

    Before you deploy, run this checklist:

    • Remove $, commas, and spaces from price input with str_replace().
    • Convert the cleaned value to a float and use round($value, 2) for precision.
    • Use number_format() to build the two-decimal numeric literal only. Do not store that result as a string in the array.
    • Inject the formatted numeric literal into the JSON string to produce xx.yy.
    • Test the JSON response in Postman or Insomnia to confirm the price is numeric and shows two decimals.
    • If your API accepts a slight variation, try JSON_PRESERVE_ZERO_FRACTION for simpler code.

    Final Thoughts

    APIs that require 900.00 instead of 900 need a targeted approach. PHP’s default float handling won’t give you fixed decimal text. Build your JSON normally, then inject the price as a two-decimal numeric literal. That change prevents integration errors and gives consistent output.

    Key points

    • number_format() returns a string, so do not place it directly into JSON.
    • PHP floats do not store formatting and drop trailing zeros.
    • Manual injection of the formatted numeric literal gives exact xx.yy text.
    • JSON_PRESERVE_ZERO_FRACTION helps but does not force two decimals.
    • Test the final JSON before you deploy.

    Leave a Reply

    Your email address will not be published. Required fields are marked *