Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
[BUGFIX] fix qgsRound for negative numbers. Fixes #20861
(cherry picked from commit cfdc8c2)
  • Loading branch information
lbartoletti authored and nyalldawson committed Feb 1, 2019
1 parent 3462511 commit 3f0171b
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/core/qgis.h
Expand Up @@ -316,8 +316,9 @@ inline bool qgsDoubleNearSig( double a, double b, int significantDigits = 10 )
*/
inline double qgsRound( double number, double places )
{
double m = ( number < 0.0 ) ? -1.0 : 1.0;
double scaleFactor = std::pow( 10.0, places );
return std::trunc( number * scaleFactor + 0.5 ) / scaleFactor;
return ( std::round( number * m * scaleFactor ) / scaleFactor ) * m;
}


Expand Down
6 changes: 4 additions & 2 deletions tests/src/core/testqgis.cpp
Expand Up @@ -339,6 +339,8 @@ void TestQgis::testQgsAsConst()

void TestQgis::testQgsRound()
{
QGSCOMPARENEAR( qgsRound( 1234.567, 2 ), 1234.57, 0.01 );
QGSCOMPARENEAR( qgsRound( -1234.567, 2 ), -1234.57, 0.01 );
QGSCOMPARENEAR( qgsRound( 98765432198, 8 ), 98765432198, 1.0 );
QGSCOMPARENEAR( qgsRound( 98765432198, 9 ), 98765432198, 1.0 );
QGSCOMPARENEAR( qgsRound( 98765432198, 10 ), 98765432198, 1.0 );
Expand All @@ -354,9 +356,9 @@ void TestQgis::testQgsRound()
QGSCOMPARENEAR( qgsRound( 9.8765432198765, 5 ), 9.87654, 0.000001 );
QGSCOMPARENEAR( qgsRound( 9.8765432198765, 6 ), 9.876543, 0.0000001 );
QGSCOMPARENEAR( qgsRound( 9.8765432198765, 7 ), 9.8765432, 0.00000001 );
QGSCOMPARENEAR( qgsRound( -9.8765432198765, 7 ), -9.876543, 0.000001 );
QGSCOMPARENEAR( qgsRound( -9.8765432198765, 7 ), -9.8765432, 0.0000001 );
QGSCOMPARENEAR( qgsRound( 9876543.2198765, 5 ), 9876543.219880, 0.000001 );
QGSCOMPARENEAR( qgsRound( -9876543.2198765, 5 ), -9876543.219870, 0.000001 );
QGSCOMPARENEAR( qgsRound( -9876543.2198765, 5 ), -9876543.219880, 0.000001 );
QGSCOMPARENEAR( qgsRound( 9.87654321987654321, 13 ), 9.87654321987654, 0.0000000000001 );
QGSCOMPARENEAR( qgsRound( 9.87654321987654321, 14 ), 9.876543219876543, 0.00000000000001 );
QGSCOMPARENEAR( qgsRound( 9998.87654321987654321, 14 ), 9998.876543219876543, 0.00000000000001 );
Expand Down

0 comments on commit 3f0171b

Please sign in to comment.