Skip to content
Permalink
Browse files

Add double to int rounding function

  • Loading branch information
NathanW2 committed Aug 26, 2012
1 parent 4f58f13 commit 91c07711ec6eb5575ba59c0a22d8b30fbdc1f088
Showing with 17 additions and 4 deletions.
  1. +15 −4 src/core/qgsexpression.cpp
  2. +2 −0 tests/src/core/testqgsexpression.cpp
@@ -777,9 +777,20 @@ static QVariant fcnGeomPerimeter( const QVariantList& , QgsFeature* f, QgsExpres

static QVariant fcnRound( const QVariantList& values , QgsFeature* f, QgsExpression* parent )
{
double number = getDoubleValue( values.at( 0 ), parent );
double scaler = pow( 10.0, getIntValue( values.at( 1 ), parent ) );
return QVariant( round( number * scaler ) / scaler );
if ( values.length() == 2 )
{
double number = getDoubleValue( values.at( 0 ), parent );
double scaler = pow( 10.0, getIntValue( values.at( 1 ), parent ) );
return QVariant( round( number * scaler ) / scaler );
}

if ( values.length() == 1 )
{
double number = getIntValue( values.at( 0 ), parent );
return QVariant( round( number) ).toInt();
}

return QVariant();
}

QList<QgsExpression::FunctionDef> QgsExpression::gmBuiltinFunctions;
@@ -802,7 +813,7 @@ const QList<QgsExpression::FunctionDef> &QgsExpression::BuiltinFunctions()
<< FunctionDef( "ln", 1, fcnLn, QObject::tr( "Math" ) )
<< FunctionDef( "log10", 1, fcnLog10, QObject::tr( "Math" ) )
<< FunctionDef( "log", 2, fcnLog, QObject::tr( "Math" ) )
<< FunctionDef( "round", 2, fcnRound, QObject::tr( "Math" ) )
<< FunctionDef( "round", -1, fcnRound, QObject::tr( "Math" ) )
// casts
<< FunctionDef( "toint", 1, fcnToInt, QObject::tr( "Conversions" ) )
<< FunctionDef( "toreal", 1, fcnToReal, QObject::tr( "Conversions" ) )
@@ -248,6 +248,8 @@ class TestQgsExpression: public QObject
QTest::newRow( "log(10,1000)" ) << "log(10,1000)" << false << QVariant( 3. );
QTest::newRow( "round(1234.557,2) - round up" ) << "round(1234.557,2)" << false << QVariant( 1234.56 );
QTest::newRow( "round(1234.554,2) - round down" ) << "round(1234.554,2)" << false << QVariant( 1234.55 );
QTest::newRow( "round(1234.6) - round up to int" ) << "round(1234.6)" << false << QVariant( 1235 );
QTest::newRow( "round(1234.6) - round down to int" ) << "round(1234.4)" << false << QVariant( 1234 );

// cast functions
QTest::newRow( "double to int" ) << "toint(3.2)" << false << QVariant( 3 );

0 comments on commit 91c0771

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