PlanetSquires Forums

Please login or register.

Login with username, password and session length
Advanced search  

Author Topic: Rounding  (Read 71 times)

Josť Roca

  • Moderator
  • Master Member
  • *****
  • Posts: 3109
    • Jos
Rounding
« on: November 28, 2018, 04:00:16 PM »

Hi Johan Klassen (aka srvaldez)

Re: https://www.freebasic.net/forum/viewtopic.php?f=7&t=27198

You can use:

Code: [Select]
' ========================================================================================
FUNCTION AfxRound (BYVAL dblValue AS DOUBLE, BYVAL numDigits AS LONG) AS DOUBLE
   IF numDigits < 1 THEN RETURN dblValue
   IF numDigits > 9 THEN numDigits = 9
   DIM nMult AS LONG = 10 ^ numDigits
   FUNCTION = FIX((nMult * dblValue + (SGN(dblValue)) * .5)) / nMult
END FUNCTION
' ========================================================================================

' ========================================================================================
FUNCTION AfxRoundToStr (BYVAL dblValue AS DOUBLE, BYVAL numDigits AS LONG) AS STRING
   IF numDigits < 1 THEN RETURN STR(dblValue)
   IF numDigits > 9 THEN numDigits = 9
   DIM nMult AS LONG = 10 ^ numDigits
   dblValue = FIX((nMult * dblValue + (SGN(dblValue)) * .5)) / nMult
   DIM strNum AS STRING = STR(dblValue)
   DIM p AS LONG = INSTRREV(strNum, ".")
   DIM nLen AS LONG = LEN(MID(strNum, p + 1))
   IF p THEN
      IF nLen < numDigits THEN strNum += STRING(numDigits - nLen, "0")
   ELSE
      strNum += "." & STRING(numDigits, "0")
   END IF
   FUNCTION = strNum
END FUNCTION
' ========================================================================================

Use as you wish. No restrictions :)
« Last Edit: November 28, 2018, 09:18:53 PM by Paul Squires »
Logged