0

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();
        }
    }
}

Basel Issmail
  • 3,847
  • 7
  • 20
  • 36
Danny
  • 11
  • 5
  • 1
    Convert input string to decimal and format it to string with two decimals- `decimal.Parse(inputString).ToString("N2")` – Fabio Jan 25 '20 at 08:04
  • Hey I attempted to use the code you suggested but received an error saying that, "Input string was not in the correct format" code ``` percentages(formula, decimal.Parse(Console.ReadLine().ToString("N2"))); ``` I appreciate the help thank you – Danny Jan 25 '20 at 08:38
  • What input string you typing in? _Input string was not in the correct format_ - is pretty clear message, which mean that given string is not valid representation of decimal value – Fabio Jan 25 '20 at 08:42
  • I was just typing in 1111.1111% and I was trying to round it to two decimal places. ex.) 1111.11% – Danny Jan 26 '20 at 05:34
  • hi danny, updated answer, check it out – Clint Jan 26 '20 at 06:22
  • You can truncate the preceding number part first, and then add `%` to the end of the string. `Console.WriteLine(decimal.Parse(input.Substring(0, input.Length - 1)).ToString("N2") + "%");` – 大陸北方網友 Jan 27 '20 at 07:19

2 Answers2

2

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
}
test_
  • 406
  • 3
  • 11
0

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")

Clint
  • 6,011
  • 1
  • 21
  • 28
  • Hey guy, I was not using info for cultures. This was for percentages and making sure that they rounded to two decimal places. Also at the end I had to make sure that there was a "%". Which you acknowledged, I just was not too sure what NumberStyles.Any and CultureInfo.InvariantCulture had to do with percentages. Regardless I appreciate the help! – Danny Jan 26 '20 at 07:35
  • I am trying to have the decimal I input round as soon as I hit enter. – Danny Jan 26 '20 at 07:46
  • Using the code above, the input is rounded as soon you enter a decimal. Example: 1111.11444 is converted to 1111.11. Number styles is tells you the different numeric representation you can add for finer control, CultureInfo.Invariant is culture-insensitive and independent of any regions. You dont have to worry about them both – Clint Jan 26 '20 at 17:51