Skip to content

Commit ff92b02

Browse files
committed
Add abs function
1 parent ebc7a35 commit ff92b02

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

resources/function_help/abs-en_US

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<h3>abs() function</h3>
2+
Returns the absolute value of a number.<br>
3+
4+
5+
<h4>Syntax</h4>
6+
abs(<i>value</i>)<br>
7+
8+
<h4>Arguments</h4>
9+
<code>value</code> - a number.<br>
10+
11+
<h4>Example</h4>
12+
<code>abs(-2) &rarr; 2</code><br>

src/core/qgsexpression.cpp

+9-1
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,13 @@ static QVariant fcnSqrt( const QVariantList& values, QgsFeature* /*f*/, QgsExpre
347347
double x = getDoubleValue( values.at( 0 ), parent );
348348
return QVariant( sqrt( x ) );
349349
}
350+
351+
static QVariant fcnAbs( const QVariantList& values, QgsFeature*, QgsExpression* parent )
352+
{
353+
double val = getDoubleValue( values.at( 0 ), parent );
354+
return QVariant( fabs( val ) );
355+
}
356+
350357
static QVariant fcnSin( const QVariantList& values, QgsFeature* , QgsExpression* parent )
351358
{
352359
double x = getDoubleValue( values.at( 0 ), parent );
@@ -1299,7 +1306,7 @@ const QStringList &QgsExpression::BuiltinFunctions()
12991306
if ( gmBuiltinFunctions.isEmpty() )
13001307
{
13011308
gmBuiltinFunctions
1302-
<< "sqrt" << "cos" << "sin" << "tan"
1309+
<< "abs" << "sqrt" << "cos" << "sin" << "tan"
13031310
<< "asin" << "acos" << "atan" << "atan2"
13041311
<< "exp" << "ln" << "log10" << "log"
13051312
<< "round" << "rand" << "randf" << "max" << "min"
@@ -1331,6 +1338,7 @@ const QList<QgsExpression::Function*> &QgsExpression::Functions()
13311338
{
13321339
gmFunctions
13331340
<< new StaticFunction( "sqrt", 1, fcnSqrt, QObject::tr( "Math" ) )
1341+
<< new StaticFunction( "abs", 1, fcnAbs, QObject::tr( "Math" ) )
13341342
<< new StaticFunction( "cos", 1, fcnCos, QObject::tr( "Math" ) )
13351343
<< new StaticFunction( "sin", 1, fcnSin, QObject::tr( "Math" ) )
13361344
<< new StaticFunction( "tan", 1, fcnTan, QObject::tr( "Math" ) )

tests/src/core/testqgsexpression.cpp

+3
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,9 @@ class TestQgsExpression: public QObject
229229

230230
// math functions
231231
QTest::newRow( "sqrt" ) << "sqrt(16)" << false << QVariant( 4. );
232+
QTest::newRow( "abs(0.1)" ) << "abs(0.1)" << false << QVariant( 0.1 );
233+
QTest::newRow( "abs(0)" ) << "abs(0)" << false << QVariant( 0. );
234+
QTest::newRow( "abs(-0.1)" ) << "abs(-0.1)" << false << QVariant( 0.1 );
232235
QTest::newRow( "invalid sqrt value" ) << "sqrt('a')" << true << QVariant();
233236
QTest::newRow( "sin 0" ) << "sin(0)" << false << QVariant( 0. );
234237
QTest::newRow( "cos 0" ) << "cos(0)" << false << QVariant( 1. );

0 commit comments

Comments
 (0)