20

Does any one know how can I format the number and limited it to only show 1 decimal place in php?

Example:

How can I format the number 2.10 to 2.1 in php?

Jin Yong
  • 42,698
  • 72
  • 141
  • 187
  • 1
    A duplicate of: http://stackoverflow.com/questions/1992406/how-do-i-format-numbers-to-have-only-two-decimal-places – jzd Jan 07 '11 at 03:47

6 Answers6

29

Use PHP's number_format

http://php.net/manual/en/function.number-format.php

Example:

$one_decimal_place = number_format(2.10, 1);

If you ever need to convert it back to a float:

$the_float_value = floatval($one_decimal_place);

Also, this article is a good reference for different decimal characters and separator styles.

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • Remove the quotes around the first argument. The first arg is a float, not a string. – Evan Mulawski Jan 07 '11 at 03:48
  • 1
    it corrects only in case of 2.10 but if the value is 2.98 then it will convert it into 3.0 so this is not the right answer here is the right answer echo bcdiv(5.98735, 1, 1); // 5.9 echo bcdiv(5.98735, 1, 2); // 5.98 – Pawan Kumar Sep 26 '19 at 07:41
8

You use the round function

echo round(3.4445, 1); // 3.4
Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
Navdeep Singh
  • 403
  • 4
  • 5
4

Number format will do this for you.

$num = 2.10;
number_format($num, 1);

PHP: number_format

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
1

you can use round() with a precision of 1, but note that some people see longer than expected result. You can also use printf() or sprintf() with a format of "%.1f"

nonopolarity
  • 146,324
  • 131
  • 460
  • 740
1

Use the PHP native function bcdiv

echo bcdiv(5.98735, 1, 1);  // 5.9
echo bcdiv(5.98735, 1, 2);  // 5.98
echo bcdiv(5.98735, 1, 3);  // 5.987
echo bcdiv(-5.98735, 1, 1); // -5.9
echo bcdiv(-5.98735, 1, 2); // -5.98
echo bcdiv(-5.98735, 1, 3); // -5.987
Pawan Kumar
  • 734
  • 9
  • 14
  • "bcdiv — Divide two arbitrary precision numbers", bit of an overkill to always divide the value by one ($num2 = divisor) just to use the 3th var – Aldo Sep 05 '22 at 11:27
0

Use number_format function. number_format("2.10", 1) will simply do that. Here is the documentation.

Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86