[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1031
  • Last Modified:

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?

Thanks in advance,
- Graham
0
topazg
Asked:
topazg
1 Solution
 
Lee SavidgeCommented:
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
 
  '-- Reconsitute final answer --
  FormatSF = FormatSF * intSign
 
  '-- 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"))
  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>
<head>
</head>
<body bgcolor="FFFFFF">
  <%=FormatSF(0.000123, 2)%>
</body>
</html>


Regards,

Lee
0
 
topazgAuthor 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"))

By adjusting:

  '-- Reconsitute final answer --
  FormatSF = FormatSF * intSign

to:

  '-- Reconsitute final answer --
  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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now