Is there a way to round to, say, 3 significant figures in .net (f# specifically) BEFORE a decimal point?
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.
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.
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))
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.
精彩评论