Sprintf php 2 decimal places

If still somebody reach this page with similar problems where floating number subtraction causes error or strange values. I want to explain this problem with a bit more details. The culprit is the floating point numbers. And different operating systems and different versions of programming languages can behave differently.

To illustrate the problem, I will explain why with a simple example below.

It is not directly related to PHP and it is not a bug. However, every programmer should be aware of this issue.

This problem even took many lives two decades ago.

On 25 February 1991 this problem in floating number calculation in a MIM-104 Patriot missile battery prevented it intercepting an incoming Scud missile in Dhahran, Saudi Arabia, contributing to the death of 28 soldiers from the U.S. Army's 14th Quartermaster Detachment.

But why it happens?

The reason is that floating point values represent a limited precision. So, a value might not have the same string representation after any processing. It also includes writing a floating point value in your script and directly printing it without any mathematical operations.

Just a simple example:

$a = '36';
$b = '-35.99';
echo ($a + $b);

You would expect it to print 0.01, right? But it will print a very strange answer like 0.009999999999998

Like other numbers, floating point numbers double or float is stored in memory as a string of 0's and 1's. How floating point differs from integer is in how we interpret the 0's and 1's when we want to look at them. There are many standards how they are stored.

Floating-point numbers are typically packed into a computer datum as the sign bit, the exponent field, and the significand or mantissa, from left to right....

Decimal numbers are not well represented in binary due to lack of enough space. So, uou can't express 1/3 exactly as it's 0.3333333..., right? Why we can't represent 0.01 as a binary float number is for the same reason. 1/100 is 0.00000010100011110101110000..... with a repeating 10100011110101110000.

If 0.01 is kept in simplified and system-truncated form of 01000111101011100001010 in binary,when it is translated back to decimal, it would be read like 0.0099999.... depending on system (64bit computers will give you much better precision than 32-bits). Operating system decides in this case whether to print it as it sees or how to make it in more human-readable way. So, it is machine-dependent how they want to represent it. But it can be protected in language level with different methods.

If you format the result, echo number_format(0.009999999999998, 2); it will print 0.01.

It is because in this case you instruct how it should be read and how precision you require.

  1. HowTo
  2. PHP Howtos
  3. Show a Number to Two Decimal Places in PHP

Created: April-29, 2020 | Updated: December-10, 2020

  1. Use number_format() Function to Show a Number to Two Decimal Places in PHP
  2. Use round() Function to Show a Number to Two Decimal Places in PHP
  3. Use sprintf() Function to Show a Number to Two Decimal Places in PHP

In this article, we will introduce methods to show a number to two decimal places in PHP.

  • Using number_format() function
  • Using round() function
  • Using sprintf() function

Use number_format() Function to Show a Number to Two Decimal Places in PHP

The built-in function number_format() is used to format a number. By formatting, we mean that the number is displayed with a decimal point and a thousand separator. It also rounds a number if needed. We can use this function to show a number to two decimal places. The correct syntax to use this function is as follows

number_format($number, $NumOfDecimals, $decimalIndicator, $thousandSeparator)
ParmaterDescription
$number mandatory the number to be formatted
$NumOfDecimals optional the number of decimal values after decimal point
$decimalIndicator optional a custom decimal point for the number. If omitted, the decimal point by default is .
$thousandSeparator optional a custom thousand separator. If omitted, the thousand separator by default is ","

Example Codes:


This function has three optional parameters but it does not allow three parameters. It allows one, two, and four parameters to be passed. In this example, the $number1 and $number2 are formatted to two decimal places with the default decimal point. But $number3 is formatted with custom decimal point "d" and thousand separator "@".

Output:

The number 5 after formating is: 5.00 
The number 34.6 after formating is: 34.60 
The number 15439.093 after formating is: 15@439d09

Use round() Function to Show a Number to Two Decimal Places in PHP

The round() function is used to round a number or float value. We can round a number to our desired decimal places. The correct syntax to use this function is as follows

round($number, $decimalPlaces, $mode);
ParmaterDescription
$number mandatory the number to be formatted
$decimalPlaces optional the number of decimal values after decimal point
$mode optional rounding mode

Example Codes:


The important thing to note here is that it does not affect a number or a float value with one decimal point if we want to round these to two decimal places.

Output:

The number 5 after rounding is: 5 
The number 34.6 after rounding is: 34.6 
The number 15439.093 after rounding is: 15439.09

Attention

When the original number has fewer decimal digits than the decimal places to be formatted, round() function will not add zeros at the end of the number.

You should use the number_format() method if two decimal places are needed for all numbers including integers.

Use sprintf() Function to Show a Number to Two Decimal Places in PHP

The built-in function sprintf() formats a string according to a given format. It can be used to show a number to two decimal places. The correct syntax to use this function is as follows

sprintf($format, $parameter1, $parameter2, ... , $parameterN);

The parameter $format is the format that specifies how the variables will be in the string. The next parameter $parameter1 is the first variable whose value will be assigned to the first % in the string. The parameter $parameter2 is the second variable whose value will be assigned to the second % in the string. In this way, we can insert N variables for N % signs.


Here, we have used %f for a float value. %.2f indicates that the float value will be up to two decimal places.

Output:

The number up to two decimal places is 67.00

Related Article - PHP Number

  • Convert a String to a Number in PHP
  • Round Floating-Point Numbers in PHP
  • Sprintf php 2 decimal places

    How can I get only 2 decimal places in PHP?

    php $num = 67; $number = sprintf('%. 2f', $num); echo "The number upto two decimal places is $number"; ?>

    How does PHP calculate float value?

    Dealing with floating-point calculations in PHP.
    1 – work on Integers. echo intval((0.1*10) + (0.7*10)); // int(8) ... .
    2 – the round() function. echo intval(round((0.1+0.7)*10, 0)); // int(8) ... .
    3 – casting to string. echo intval(strval((0.1+0.7)*10)); // int(8) ... .
    4 – BC Math. ... .
    Summary..

    How do I put 2 decimal places in HTML?

    1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number is round to 2 decimal places.

    What is precision PHP?

    Precision is defined as the number of significant digits, and scale is the number of digits behind the decimal point. This means that a number like “1.23E-1000” would require a scale of 1002 but a precision of 3. Decimal uses precision, where bcmath uses scale.