6

I need to do deviding:

{math equation="x/y" x=$x y=$y} // $x = '2', $y = '3'

How to convert strings to numbers exactly in Smarty, coz I don't have access to proprietary code of CMS? Thanx!

UPD: Smarty version: 2.6.18

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
Sergey Kudryashov
  • 713
  • 2
  • 9
  • 30
  • int typecast inside equation is allowed (see here: http://smarty-php.googlecode.com/svn/tags/Smarty_2_6_18/libs/plugins/function.math.php) so you could simple do this `{math equation="(int)x/(int)y" x=$x y=$y}` – sofl May 16 '14 at 13:17
  • @sofl has probably **the most *readable* and *efficient* solution**. The *shortest* way is to multiply it by `1`, because number multiplied by `1` always remains the same and `*` operator is for numbers-only so the variables that are not already numbers get converted. `{math equation="x/y" x=$x*1 y=$y*1}` – jave.web Nov 28 '16 at 00:04

3 Answers3

13

If it's already assigned to a variable, say $var, you can set the type of a variable like this:

{$converted = settype ($var, 'integer')}

You don't have to use the $converted value, but if you don't assign it, the bool will show up in your page.

or you could try

{$variable|intval}
Guns
  • 2,678
  • 2
  • 23
  • 51
4

You can try this {$variable|intval}

and also ((int)$variable)

For Instance:

$x_new = (int) $x;
$y_new = (int) $y;

In your case:

{math equation="x/y" x=(int)$x y=(int)$y}
Manwal
  • 23,450
  • 12
  • 63
  • 93
3

It works without modifications in:

PHP:

$x = '2' ;
$y = '3' ;

$smarty->assign('x',$x);
$smarty->assign('y',$y);

$smarty->display('index.tpl');

Smarty:

{math equation="x/y" x=$x y=$y}

Displayed result is: 0.66666666666667

It was tested in the last available Smarty version 2.6.28

So you should consider trying upgrading to the newest Smarty (of course you have to backup everything in case it will cause any problems) because there were many bugs in older versions.

You also in your question haven't written what results shows you smarty and what are variables x and y values displayed in Smarty/

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291