3

In excel the function call "=round(12345,-3)" would resolve to "12000". That is, the -3 rounding parameter allows the application of significant figures before the decimal point.

Does anyone know of an easy way (i.e. existing library call rather than a writing a custom divide/round/multiply function) to do this in f#?

Math.Round (12345, -3) fails because the second value in the tuple is required to be positive.

3
  • 1
    For what its worth what you are describing is not rounding to 3 significant figures in a mathematical sense. 3 signifigant figures would be the first three figures in the number so in this case 12300.
    – Chris
    Jul 7, 2011 at 9:56
  • As for the question the only thing I can think of would be a function that takes a power and does something like "(Math.Round(12345*(10^-3))/10^-3)" but I can't put that into F# syntax and I don't know if that is considered easy since it requires writing a whole new function and potentially introducing fun rounding errors, etc.
    – Chris
    Jul 7, 2011 at 9:58

3 Answers 3

4

You can use the "G" standard format string to specify a number of significant digits. For example:

String.Format("{0:G3}", value)

Obviously this gives you a string as the output. Maybe that's what you were going to do with it anyway, or if not you can convert it back to a number with Int32.Parse() or similar.

There is also the answer to this question, which although in C# should be fairly simple to convert as it's all .NET Framework method calls.

1

This would be my approach. possibly not the best for everyone. Also actually rounds the number not a string format.

// Rounding function that takes a significant figure count (sF)

let roundToSigFigs(x : float, sigFigs : byte) = 
    let absx = System.Math.Abs(x)
    System.Math.Round(0.5 + System.Math.Log10(absx))
    |> fun c -> float(c)-float(sigFigs)
    |> fun d  -> System.Math.Round(absx * 10.0**(-d)) * 10.0**d
    |> fun a -> a * float(System.Math.Sign(x))
0

Luca Bolognese implemented all the Excel financial functions in F#. Chances are this includes the rounding function you'd like to use, with the same behavior as Excel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.