Sam Greaves
Sam Greaves

Reputation: 13

How do I make my percentages have 2 decimal points?

I have looked at other posts about this but i just can't get my head around it and wanted to ask specifically for my scenario. I have written a Visual Basic console application and I am trying to get my percentages to have two decimal places on them as they're just rounding up to the nearest whole number. Here is the code :

Console.Write("Enter the percentage you want to work out: ")
Dim Percentage As Integer
Percentage = Console.ReadLine()

Console.Write("What would you like to work out " & Percentage & "% of? ")
Dim Number As Integer
Number = Console.ReadLine()

Dim PercentageNumberResult As Integer
PercentageNumberResult = Number / 100 * Percentage

Console.Write(Number & " ÷ 100 × " & Percentage & " = " & PercentageNumberResult)
Console.ReadLine()

Any help would be appreciated, thanks!

Upvotes: 0

Views: 3417

Answers (2)

jmcilhinney
jmcilhinney

Reputation: 54417

If you want to convert a number to a String then you call ToString on that number. If you want a specific format then you pass the appropriate format specifier as an argument when calling ToString. You should read the relevant documentation to learn all the possible format specifiers.

In this case, you display a number as a percentage using the "p" or "P" specifier and you can add a number to specify the number of decimal places. e.g.

Dim x = 13
Dim y = 1000
Dim z = x / y
Dim s = z.ToString("P2")

After executing that code, s will contain "1.30%".

If you don't actually want the "%" symbol in the output then you can multiply by 100 and use a different format specifier, e.g.

Dim x = 13
Dim y = 1000
Dim z = 100 * x / y
Dim s = z.ToString("N2")

After executing that code, s will contain "1.30".

Upvotes: 0

Benno
Benno

Reputation: 2534

The problem is due to PercentageNumberResult being an integer.

Make PercentageNumberResult a double :

    Dim PercentageNumberResult As Double
    PercentageNumberResult = Number / 100 * Percentage

You could then use Math.Round if needed. Also you should turn on Option Strict this will help solving the problem.

Upvotes: 2

Related Questions