# Format a number to 2 Significant Figures

Dear All,

I cannot see using the formatnumber function how it is possible to format a number to 2 significant figures (not decimal places), but I cannot see any other function or an easy other way to do this either.

What would be the easiest way to format a number to 2 significant figures?

- Graham
LVL 3
###### Who is Participating?

Commented:
Hi,

I found a VB function on the web a while ago to do this. I converted it to ASP and it works just fine.

<%@ language="VBScript" %>
<%
Option Explicit

'Returns input number rounded to specified number of significant figures.
private Function FormatSF(byval dblInput, byval intSF)

Dim intCorrPower
Dim intSign

'-- Store sign of dblInput --
intSign = Sgn(dblInput)

'-- 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

FormatSF = FormatSF * intSign

If InStr(FormatSF, ".") = 0 Then
If Len(FormatSF) < intSF Then FormatSF = Format(FormatSF, "##0." & String(intSF - Len(FormatSF), "0"))
End If

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"
Loop
End If
End Function

private Function Log10(x)
Log10 = Log(x) / Log(10)
End Function

%>

<html>
<body bgcolor="FFFFFF">
<%=FormatSF(0.000123, 2)%>
</body>
</html>

Regards,

Lee
0

Author Commented:
Thanks for this ... Just as a note, it doesn't appear to work with numbers that round to exactly single digits (7 and 6.000 for example) due to not enough digits to run the following line:

If Len(FormatSF) < intSF Then FormatSF = Format(FormatSF, "##0." & String(intSF - Len(FormatSF), "0"))

FormatSF = FormatSF * intSign

to:

FormatSF = FormatSF * intSign

'-- Ensures enough decimal places after the point --
FormatSF = formatnumber(FormatSF,(intSF - 1))

This problem seems to be resolved. Great prompt answer though, cheers :)

- Graham
0
Question has a verified solution.

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.