Add abs function

This commit is contained in:
nyalldawson 2013-05-12 22:43:17 +10:00
parent ebc7a35f7b
commit ff92b029cf
3 changed files with 24 additions and 1 deletions

View File

@ -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>

View File

@ -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" ) )

View File

@ -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. );