How to express a decimal number as a fixed-length string with leading zeros in VB.NET

1 Answer

0 votes
Imports System

Module Program
	'    format_decimal_with_zeros
	'    -------------------------
	'    Converts a floating‑point number into a fixed‑length string with
	'    leading zeros on the integer part.
	'
	'    Parameters:
	'        num          - the decimal number to format
	'        width        - total width of the integer part (zero‑padded)
	'        decimals     - number of digits after the decimal point
	'
	'    Returns:
	'        A formatted string such as "00003.14159"
	'
	'    Example:
	'        num = 3.14159, width = 5, decimals = 5
	'        Output → "00003.14159"
	Function formatDecimalWithZeros(num As Double, width As Integer, decimals As Integer) As String

    	' Split into integer and fractional parts
    	Dim integer_part As Integer = CInt(Math.Truncate(num))
    	Dim fractional_part As Double = num - integer_part

    	' Format integer part with leading zeros
    	Dim int_str As String = integer_part.ToString().PadLeft(width, "0"c)

    	' Format fractional part (starts with "0.xxx")
    	Dim frac_str As String = fractional_part.ToString("F" & decimals)

    	' Remove the leading "0" before the decimal point
    	Return int_str & frac_str.Substring(1)
	End Function
	
    Sub Main()
		Dim num As Double = 3.14159

		Dim result As String = formatDecimalWithZeros(num, 5, 5)

		Console.WriteLine("Original number: " & num.ToString("F5"))
		Console.WriteLine("Formatted string: " & result)
    End Sub
End Module



' run:
'
' Original number: 3.14159
' Formatted string: 00003.14159
'

 



answered 22 hours ago by avibootz

Related questions

...