Decimal Places / Significant Figures
Overview
When working with numbers and calculations at Higher Education level, you are often asked to give your answer correct to a specified number of Decimal Places or a specified number of Significant Figures. These are simple conversions, but how do you do this in code?
The Form Code
Converting a Decimal or an Integer to a String representation of a Decimal with a specified number of Significant Figures or a specified number of Decimal Places is a one liner.
The Button1_Click code handles the conversion for Significant Figures, first parsing the TextBox's text, then converting the number to a Decimal with the correct number of figures, by calling the SignificantFigures Function nested within a call to the DecimalPlaces Function.
In a perfect world, formatting with the "g" format would be enough, but the "g" format doesn't strictly adhere to Significant Figures Rules...
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim d As Decimal
If Decimal.TryParse(TextBox1.Text, d) AndAlso d <> 0 Then
Dim s As String = TextBox1.Text
Dim fSF As Integer = Array.FindIndex(s.ToArray, Function(c As Char) c <> "0"c AndAlso c <> "."c)
Dim dp As Integer = s.IndexOf(".")
Dim l As Integer = s.Length
Dim f As Integer = CInt(NumericUpDown1.Value)
Dim places As Integer
If dp = -1 Then
places = f - l
Else
places = fSF - dp + f + If(fSF > 0, -1, 0)
End If
Dim output As Decimal = DecimalPlaces(SignificantFigures(d, f), Math.Max(places, 0))
Label1.Text = String.Format("{0} ({1} sf)", output, f)
Else
Label1.Text = "Invalid input"
End If
End Sub
Converting a Decimal to a String representation of a Decimal with a specified number of Decimal Places is another one liner.
The Button2_Click code handles the conversion for Decimal Places, first parsing the TextBox's text, then converting the number to a string using the "f" format.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim d As Decimal
If Decimal.TryParse(TextBox1.Text, d) AndAlso d <> 0 Then
Dim f As Integer = CInt(NumericUpDown1.Value)
Label1.Text = String.Format("{0} ({1} dp)", DecimalPlaces(d, f), f)
Else
Label1.Text = "Invalid input"
End If
End Sub
End Class
These are the two Functions used in the conversions.
Private Function SignificantFigures(ByVal input As Decimal, ByVal f As Integer) As Decimal
Return CDec(input.ToString("g" & f.ToString))
End Function
Private Function DecimalPlaces(ByVal input As Decimal, ByVal p As Integer) As Decimal
Return CDec(input.ToString("f" & p.ToString))
End Function
See Also
The Fixed-Point ("F") Format Specifier
The General ("G") Format Specifier