Michael Shtefanitsa
Michael Shtefanitsa

Reputation: 303

Decimal place VB.NET simple

I know that is the simple question but how can i return sum of my variable d with decimal places ? it's always return me 8, not 8.0. But if my variable will be for examle 4.1 it will return 8.2 how it works with 0 in VB.NET?

Public Shared Sub Main()
    Dim d As Decimal = 4.0
    Console.WriteLine(d+d)
End Sub

Upvotes: 0

Views: 1116

Answers (3)

Rhurac
Rhurac

Reputation: 449

To expand on David's answer, you can manipulate the output of any string you want by changing the first argument of String.Format. For example, if you want two decimal places you can use:

String.Format("{0:0.00}", d+d)

for three decimal places:

String.Format("{0:0.000}", d+d)

The number before the colon corresponds to the argument number. The numbers after the colon specify the format you want. For example with two arguments using different formats:

String.Format("{0:0.0}, {1:0.00}", d, n)

If you had d=4 and n=2 and you printed this out using the above formatter, you would end up with 4.0 (corresponding to the 0 argument with 0.0 format) and a 2.00 (corresponding to the 1 argument with 0.00 format)

and so on. There are a ton of options, not only for numbers, but for dates and more. Check out this easy-to-read website to understand its use a bit more clearly.

Hope this helps!

Upvotes: 0

Aaditya Dengle
Aaditya Dengle

Reputation: 136

use Decimal.ToString() method while writing to console.

Upvotes: 1

David
David

Reputation: 2324

Try something like this, pass the decimal in as a string, or else modify this function, but this should do the trick

Private Function ConvertStringToDec(str As String) As Decimal
   Dim temp As String = String.Format(".{0}", str)
   Dim d As Decimal
   Decimal.TryParse(temp, d)
     Return dec
End Function

Upvotes: 0

Related Questions