Skip to content
Permalink
Browse files

Add abs function

  • Loading branch information
nyalldawson committed May 12, 2013
1 parent ebc7a35 commit ff92b029cfa5584058ac0fb7eb414c7340af3a33
Showing with 24 additions and 1 deletion.
  1. +12 −0 resources/function_help/abs-en_US
  2. +9 −1 src/core/qgsexpression.cpp
  3. +3 −0 tests/src/core/testqgsexpression.cpp
@@ -0,0 +1,12 @@
<h3>abs() function</h3>
Returns the absolute value of a number.<br>


<h4>Syntax</h4>
abs(<i>value</i>)<br>

<h4>Arguments</h4>
<code>value</code> - a number.<br>

<h4>Example</h4>
<code>abs(-2) &rarr; 2</code><br>
@@ -347,6 +347,13 @@ static QVariant fcnSqrt( const QVariantList& values, QgsFeature* /*f*/, QgsExpre
double x = getDoubleValue( values.at( 0 ), parent );
return QVariant( sqrt( x ) );
}

static QVariant fcnAbs( const QVariantList& values, QgsFeature*, QgsExpression* parent )
{
double val = getDoubleValue( values.at( 0 ), parent );
return QVariant( fabs( val ) );
}

static QVariant fcnSin( const QVariantList& values, QgsFeature* , QgsExpression* parent )
{
double x = getDoubleValue( values.at( 0 ), parent );
@@ -1299,7 +1306,7 @@ const QStringList &QgsExpression::BuiltinFunctions()
if ( gmBuiltinFunctions.isEmpty() )
{
gmBuiltinFunctions
<< "sqrt" << "cos" << "sin" << "tan"
<< "abs" << "sqrt" << "cos" << "sin" << "tan"
<< "asin" << "acos" << "atan" << "atan2"
<< "exp" << "ln" << "log10" << "log"
<< "round" << "rand" << "randf" << "max" << "min"
@@ -1331,6 +1338,7 @@ const QList<QgsExpression::Function*> &QgsExpression::Functions()
{
gmFunctions
<< new StaticFunction( "sqrt", 1, fcnSqrt, QObject::tr( "Math" ) )
<< new StaticFunction( "abs", 1, fcnAbs, QObject::tr( "Math" ) )
<< new StaticFunction( "cos", 1, fcnCos, QObject::tr( "Math" ) )
<< new StaticFunction( "sin", 1, fcnSin, QObject::tr( "Math" ) )
<< new StaticFunction( "tan", 1, fcnTan, QObject::tr( "Math" ) )
@@ -229,6 +229,9 @@ class TestQgsExpression: public QObject

// math functions
QTest::newRow( "sqrt" ) << "sqrt(16)" << false << QVariant( 4. );
QTest::newRow( "abs(0.1)" ) << "abs(0.1)" << false << QVariant( 0.1 );
QTest::newRow( "abs(0)" ) << "abs(0)" << false << QVariant( 0. );
QTest::newRow( "abs(-0.1)" ) << "abs(-0.1)" << false << QVariant( 0.1 );
QTest::newRow( "invalid sqrt value" ) << "sqrt('a')" << true << QVariant();
QTest::newRow( "sin 0" ) << "sin(0)" << false << QVariant( 0. );
QTest::newRow( "cos 0" ) << "cos(0)" << false << QVariant( 1. );

0 comments on commit ff92b02

Please sign in to comment.
You can’t perform that action at this time.