Skip to content

Commit

Permalink
Add abs function
Browse files Browse the repository at this point in the history
  • Loading branch information
nyalldawson committed May 12, 2013
1 parent ebc7a35 commit ff92b02
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
12 changes: 12 additions & 0 deletions resources/function_help/abs-en_US
Original file line number Diff line number Diff line change
@@ -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>
10 changes: 9 additions & 1 deletion src/core/qgsexpression.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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" ) )
Expand Down
3 changes: 3 additions & 0 deletions tests/src/core/testqgsexpression.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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. );
Expand Down

0 comments on commit ff92b02

Please sign in to comment.