[英]keeping the decimal when creating a string in VB.NET
我需要創建一個由各種變量組成的字符串,並且需要用前導零填充,如果小數點后的值為零,我還需要保留小數。 如果變量只是零,那么我想完全抑制它並用空格填充
例如:
如果我在變量中得到0且大小為3,我希望字符串為:“”如果我在變量中得到9且大小為3,那么我想要字符串:“ 009”如果我得到的變量為90.0而它是大小說10,然后我要字符串:“ 00000090.0”
我正在嘗試使用:
public function PadField(byval field as object, byval size as int16) as string
dim fieldstring as string = string.empty
dim fieldDate as date
' here I want to check for a numeric variable
if isnumeric(field) then
' if the variable is an integer with a value of zero...
if cint(field) = 0 then
stringField = string.empty.padleft(size,"0")
' else if the variable is an integer greater than zero...
elseif cint(field) > 0 then
stringField = field.toString.padLeft(size,"0")
End If
' else if a date, I want date to look like MM/dd/yyyy...
elseif IsDate(field) then
fieldDate = field
strigField = fieldDate.ToString("MM/dd/yyyy")
' else if a string, then I want to pad after with spaces
else
stringField = field.ToString.Trim.toUpper.PadRight(size," ")
End If
return stringField
end Function
問題是當我傳入類似1234.0的變量時,得到以下結果:
"0001234"
但我想要:
"0001234.0"
如果我發送1234.1,那么它可以工作,如果我發送1,我得到“ 0001234.1”,如果我發送90,我想得到“ 001”,如果我發送日期,我想得到“ 090”,我想如果我發送一個字符串,將得到“ 08/21/2012”,我想得到“ NAME”
當小數為零時,有人可以幫助保留小數嗎?
如果小數點位數發生變化,您將必須實現一些更詳細的說明,但是如果您可以使用兩個小數點,則可以使用:
stringField = CDbl(field).ToString("0.00").PadLeft(size, "0")
我無法重現該行為,您的字符串是否有可能在某處轉換為數字數據類型? 如果我將“ 123.0”傳遞給下面的例程,則會得到00000123.0。 在我看來,問題出在別的地方。
Public Sub test(o As Object)
If IsNumeric(o) Then
If (CInt(o)) > 0 Then
MessageBox.Show(o.ToString.PadLeft(10, CChar("0")))
End If
End If
End Sub
如PatFromCanada所說,如果將其作為字符串傳遞,則可以。 如果將其作為整數傳遞,則將其推斷為整數,而不是字符串。 那不是你想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.