2

I need to convert numbers to have .00 after them, but only if the number is an integer, or it has just 1 number after the decimal point, like so:

1.4 = 1.40
45 = 45.00
34.77 = 34.77

What reg exp to use for this simple case?

WraithLux
  • 699
  • 4
  • 15
  • 22

5 Answers5

2

You can also use printf or sprintf

printf("%01.2f", '34.77');
$formatted_num = sprintf("%01.2f", '34.77');
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
  • Good call -- runs about 40% faster than `number_format()` if you don't need that thousands separator. – Kelly May 18 '11 at 14:55
1
number_format($number, 2, '.', '');

Read more at PHP.net. You don't need to determine if a number is an integer or not -- as long as it's a number, it will be formatted to two decimal places.

If you'd like the thousands separator, change the last parameter to ','.

Kelly
  • 40,173
  • 4
  • 42
  • 51
1

Check out PHP's built-in function number_format

You can pass it a variable and it'll format it to the correct decimal places

    $number = 20;
    if (is_int($number)) {
        $number = number_format($number, 2, '.', '');
    }
fin1te
  • 4,289
  • 1
  • 19
  • 16
0
$num = 0.00638835;

$avg = sscanf($num,"%f")[0] /100;

echo sprintf("%.10f", $avg);

result 0.0000638835
ilgice
  • 31
  • 2
  • 5
  • 1
    can you explain what you are doing and how this works – MZaragoza Dec 22 '17 at 00:16
  • sscanf — Parses input from a string according to a format – ilgice Dec 22 '17 at 10:38
  • The function sscanf() is the input analog of printf(). sscanf() reads from the string str and interprets it according to the specified format, which is described in the documentation for sprintf(). – ilgice Dec 22 '17 at 10:38
  • `echo sprintf()` is an "antipattern". There is absolutely no reason that anyone should ever write `echo sprintf()` -- it should be `printf()` without `echo` every time. – mickmackusa Apr 16 '22 at 03:11
0

read number_format

number_format($number, 2, '.', '');
xkeshav
  • 53,360
  • 44
  • 177
  • 245