sqlvisual-foxprofoxpro

FoxPro how to accomplish equivalent to Excel ROUNDUP and ROUNDDOWN


I am hoping to accomplish the equivalent of Microsoft Excel's ROUNDUP and ROUNDDOWN functions. Right now I am using the following:

roundup_val = ROUND(val + 0.005,2)

which will round up a positive value to the second decimal place since 0.005 is being added to the value. However, this does not work correctly if the value only has 2 decimal places or left. For example, Excel's ROUNDUP to 2 decimal places on a value, val = 20.01, will return the same value, ROUNDUP(20.01,2) = 20.01. My method above will return ROUND(20.015,2) = 20.02, which is incorrect.

I think this method will work if I include more code to check wether the number has less than three decimal places and then it will simply keep the same number since it is already rounded to the second place. If I'm to do this, I was also wondering how I can check how many decimal places long a number is.

It is also possible that this method is not the best way to accomplish a FoxPro version of ROUNDUP. Are there any other ideas out there that will work on all numbers?

Thanks!


Solution

  • You are right VFP doesn't have RoundUp() and RoundDown() functions. But they are very easy to create. I had this already at my backyard:

    *ROUNDUP.PRG
    Lparameters tnValue, tnPlaces
    Local lnResult, lnValue
    lnValue = Abs(m.tnValue)
    If Round(m.lnValue, m.tnPlaces) != m.lnValue
        lnValue = Round(m.lnValue+((10^-(m.tnPlaces+1))*5), m.tnPlaces)
    EndIf
    Return Sign(m.tnValue) * m.lnValue
    
    *ROUNDDOWN.PRG
    Lparameters tnValue, tnPlaces
    Local lnResult, lnValue
    lnValue = Abs(m.tnValue)
    If Round(m.lnValue, m.tnPlaces) != m.lnValue
        lnValue = Round(m.lnValue-((10^-(m.tnPlaces+1))*5), m.tnPlaces)
    EndIf
    Return Sign(m.tnValue) * m.lnValue
    

    Just save these as roundup.prg and rounddown.prg, and you have ROUNDUP(), ROUNDDOWN() functions as Excel's.