Danny
Danny

Reputation: 11

How to convert to two decimal places

How I can get the value that the user inputs to round to two decimal places. I tried to use.ToString("N2") but it gave me an error of {cannot convert string to System.IFormatProvider}. I can't seem to find a solution to this error.

code is here:


using System;
using System.Text.RegularExpressions;

namespace _selfTest
{
    class Program
    {
        public static void Main(string[] args)
        {
            const string formula = @"^\d+\.?\d+?\%$";

            percentages(formula, Console.ReadLine());
        }


        public static void percentages(string bottle, string flower)
        {
            Regex newRegular = new Regex(bottle);
            bool input = newRegular.IsMatch(flower);

            if (input)
                Console.WriteLine("This Percentage Is Correct! " + bottle);
            else
                Console.WriteLine("This Percentage Is Incorrect... " + bottle);

            Console.ReadLine();
        }
    }
}

Upvotes: 0

Views: 1295

Answers (2)

Clint
Clint

Reputation: 6499

Your solution is just 2 steps away

  • Parsing the user input to decimal format
  • Then rounding off to 2 decimal places

.cs

    static void Main(string[] args)
    {


        //Parse User input
        var inputValue = Console.ReadLine();
        inputValue = inputValue.Split('%')[0]; //To handle the trailing % sign

        decimal outputValue;
        var style = NumberStyles.Any;
        var culture = CultureInfo.InvariantCulture;
        if (Decimal.TryParse(inputValue, style, culture, out outputValue))
            Console.WriteLine("Converted '{0}' to {1}.", inputValue, outputValue);
        else
            Console.WriteLine("Unable to convert '{0}'.", inputValue);

        //Rounding off 2 decimal places

        var roundedValue = Math.Round(outputValue, 2);
        Console.WriteLine(roundedValue);
        Console.Read();

    }

Note

If you know ahead of time what culture you expect your inputs to be in you can specify that using culture info

var culture = new CultureInfo("en-US");// or ("fr-FR")

Upvotes: 0

test_
test_

Reputation: 416

You could use Decimal.TryParse method. And then you can use standard numeric format string "N2"

string consoleInput = Console.ReadLine();
if(Decimal.TryParse(consoleInput, out decimal parsedInput))
{
   string resultString = parsedInput.ToString("N2");
}
else
{
   // handling bad input
}

Upvotes: 2

Related Questions