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.

Vijesh
  • 251
  • 2
  • 8
  • 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 07 '11 at 09: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 07 '11 at 09:58
  • http://stackoverflow.com/questions/374316/round-a-double-to-x-significant-figures-after-decimal-point/1925170#1925170 – Daniel Jul 07 '11 at 14:21

3 Answers3

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.

Community
  • 1
  • 1
Jon Grant
  • 11,369
  • 2
  • 37
  • 58
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))
Steve
  • 11
  • 1
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.

Joel Mueller
  • 28,324
  • 9
  • 63
  • 88