# VB Significant Digits function

Does anyone have a visual basic function that will return a passed number with a requested number of significant digits?
For example:
X = 1.233412
Y = FixSigFigs(X,3) 'I want Y to have 3 significant digits.

Function FixSigFigs( NumberToFix as double, SigFigs as Integer)

###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
Round Function

Returns a number rounded to a specified number of decimal places.
Round(expression [,numdecimalplaces])

Dim MyVar, pi
pi = 3.14159
MyVar = Round(pi, 2) ' MyVar contains 3.14.

High School Computer Science, Computer Applications, and Mathematics TeachersCommented:
Public Function FixSigFigs(NumberToFix As Double, SigFigs As Integer) As Double
Dim textNumber As String
Dim decimalPlace As Integer
Dim digitsToRight As Integer

FixSigFigs = NumberToFix ' If no change, return original number
textNumber = CStr(NumberToFix)
decimalPlace = InStr(textNumber, ".")
If decimalPlace > 0 Then
digitsToRight = Len(textNumber) - decimalPlace
If digitsToRight > SigFigs And SigFigs >= 0 Then
FixSigFigs = CDbl(Left(textNumber, decimalPlace + SigFigs))
End If
End If
End Function
High School Computer Science, Computer Applications, and Mathematics TeachersCommented:
You didn't specify as to whether you wanted rounding or not.  Use the Round() function, as AlexFM suggested, if you need rounding to occur.  Otherwise, use my function if you simply want to truncate the number to the requested number of digits.
Commented:
hello kar8942 !

That isn't a simple task in general.
Of course you can use the built in round function of vb.
But this function isn't country-independent.

Example:

? round(1.145,2)
1,14
? round(1.245,2)
1,25

In germany for example round(1.145,2) should be 1.15.
Therefore i wrote a user defined function:

Public Function RoundIt(Number As Variant, ByVal NumDigitsAfterDecimal As Long) As Variant
Select Case True
Case Not IsNumeric(Number)
RoundIt = Number
Case Else
NumDigitsAfterDecimal = 10 ^ NumDigitsAfterDecimal
RoundIt = Int(CDec(CDec(0.5) + CDec(Number) * CDec(NumDigitsAfterDecimal))) / CDec(NumDigitsAfterDecimal)
End Select
End Function

regards

V.K.

Experts Exchange Solution brought to you by