31

Is it possible to format a number to 2 decimal places with Smarty PHP?

Thanks.

plosww1
  • 343
  • 1
  • 3
  • 7

4 Answers4

58

string_format accepts sprintf formatting options:

{$number|string_format:"%.2f"}
jasonbar
  • 13,333
  • 4
  • 38
  • 46
  • This does not work with numbers containing less than 2 decimal places. (ie. 1.9) – hendr1x Jun 05 '14 at 19:25
  • Yes it does. It turns `1.5` into `1.50`. – Peon Mar 10 '15 at 10:21
  • 2
    Remember that if you want to place an expression in place of the plain variable `$number`, you should wrap them into parenthesis, like: `{($a/$b)|string_format:"%.2f"}` – Marco Marsala Dec 05 '16 at 10:19
  • Hi. Is there any way for this filter to work like this with one exception. In case the number is integer to display it like that? Meaning if the number is 2, display 2 instead of 2.00 ? – paulalexandru Feb 14 '17 at 20:00
  • Didn't work for me, I got an error about the modifier not existing. Is it only certain versions of Smarty perhaps? – Abhi Beckert Jan 21 '20 at 00:41
31

{$number|number_format:2} is what you want

user889915
  • 319
  • 3
  • 2
  • Remember that if you want to place an expression in place of the plain variable `$number`, you should wrap them into parenthesis, like: `{($a/$b)|number_format:2}` – Marco Marsala Dec 05 '16 at 10:20
  • This didn't work for me, it formatted the number with zero decimal places ignoring the parameter. – Abhi Beckert Jan 21 '20 at 00:42
14

You can use the round function, though it will not add decimal places only remove them:

{$number|round:2}

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
Wireblue
  • 1,329
  • 1
  • 14
  • 24
  • 1
    This answer is more appropriate as it is dealing with numbers rounding and treating numbers as numbers instead of strings. – inam101 Jul 03 '13 at 12:14
  • 1
    Remember that if you want to place an expression in place of the plain variable `$number`, you should wrap them into parenthesis, like: `{($a/$b)|round:2}`. Quotes around `2` aren't mandatory – Marco Marsala Dec 05 '16 at 10:20
  • 1
    Does not change 123 to 123.00 – Andrew Sep 17 '18 at 20:22
  • 2
    This does rounding but doesn't format a number to 2 decimal places as the OP asked. (It doesn't add zeros to the end when necessary.) And `string_format` seems to round sometimes and not others. This does both: `{$number|round:"2"|string_format:"%.2f"}` – Russell G Oct 09 '19 at 17:55
  • This was the only answer that actually worked on the version of Smarty I'm running... and it did round to 2 decimal places. – Abhi Beckert Jan 21 '20 at 00:42
-3

To display 2 instead of 2.00 you can use : replace in Smarty PHP

See below example -

$number = 2.00

{$number|replace:'.00':''}

Output :- 2 

Hope this helps.