Go Premium for a chance to win a PS4. Enter to Win

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

vb,net convert money to string

Hi experts
I have a table field hour format money and it has a value 5.4800 stored to it,
I would like convert that to a string but only 2 decimals i,e 5.48
I am using the following code to get this value. I was wondering if their is an easy and shorter way to doing it,


       Dim hoursxx = row("Hours").ToString
                Dim lhx = Len(hoursxx)
                Dim lhxx = Microsoft.VisualBasic.Left(hoursxx, lhx - 2)

lhxx returns 5.68

thanks
0
b001
Asked:
b001
  • 2
1 Solution
 
Neil RussellTechnical Development LeadCommented:
Dim hoursxx = row("hours")
Dim str1 as string
str1 = Format(hoursxx, "##,##0.00")

Open in new window


58.9800 would give "58.98"
0
 
it_saigeDeveloperCommented:
Whenever doing these types of conversions, it is better to do a type and exception safe conversion, in your case:
Dim hoursxx = row("hours")
Dim formatter As Decimal
Dim converted As String = If(Decimal.TryParse(hoursxx, formatter), formatter.ToString("0.00"), "Invalid decimal/money value")

Open in new window


Example program -
Module Module1
	Private money1 As String = "58.98000"
	Private money2 As String = "145.00"
	Private money3 As String = "45.789032"
	Private money4 As String = "I am not money"

	Sub Main()
		Dim format As Decimal = Decimal.MinValue
		Console.WriteLine("Money 1 is - {0}", If(Decimal.TryParse(money1, format), format.ToString("0.00"), "Not a decimal/money value"))
		Console.WriteLine("Money 2 is - {0}", If(Decimal.TryParse(money2, format), format.ToString("0.00"), "Not a decimal/money value"))
		Console.WriteLine("Money 3 is - {0}", If(Decimal.TryParse(money3, format), format.ToString("0.00"), "Not a decimal/money value"))
		Console.WriteLine("Money 4 is - {0}", If(Decimal.TryParse(money4, format), format.ToString("0.00"), "Not a decimal/money value"))
		Console.ReadLine()
	End Sub
End Module

Open in new window


Produces the following output -Capture.JPG
-saige-
0
 
Neil RussellTechnical Development LeadCommented:
@it_saige
If you read the question, the data was coming from a Monet type database field. So it is not going to contain "I am not money" hence I never made assumptions about type and gave what was required for this scenario.
Had the source of the data been unknown then yes, yours would be safe.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

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