Experts Exchange connects you with the people and services you need so you can get back to work.
Dim a As Double
a = 12.333
MsgBox (FormatNumber(a, 2))
'gives Output as 12.33
Open in new window
'Returns input number rounded to specified number of significant figures.
Function FormatSF(dblInput As Double, intSF As Integer) As String
Dim intCorrPower As Integer 'Exponent used in rounding calculation
Dim intSign As Integer 'Holds sign of dblInput since logs are used in calculations
FormatSF = "0" 'default
'-- Store sign of dblInput --
intSign = Sgn(dblInput)
If dblInput <> 0# Then 'dblInput cannot be zero or Log10 will crash
'-- Calculate exponent of dblInput --
intCorrPower = Int(Log10(Abs(dblInput)))
FormatSF = Round(dblInput * 10 ^ ((intSF - 1) - intCorrPower)) 'integer value with no sig fig
FormatSF = FormatSF * 10 ^ (intCorrPower - (intSF - 1)) 'raise to original power
'-- Reconsitute final answer --
'FormatSF = FormatSF * intSign 'deactivated to fix negative values
'-- Answer sometimes needs padding with 0s --
If InStr(FormatSF, ".") = 0 Then
If Len(FormatSF) < intSF Then
FormatSF = Format(FormatSF, "##0." & String(intSF - Len(FormatSF), "0"))
If intSF > 1 And Abs(FormatSF) < 1 Then
Do Until Left(Right(FormatSF, intSF), 1) <> "0" And Left(Right(FormatSF, intSF), 1) <> "."
FormatSF = FormatSF & "0"
Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.
Have a better answer? Share it in a comment.
Please enter a first name
Please enter a last name
Must be at least 4 characters long.
Join and Comment
Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.