简体   繁体   English

如何转换为两位小数

[英]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}.我尝试使用.ToString("N2") 但它给了我一个错误 {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();
        }
    }
}

You could use Decimal.TryParse method.您可以使用Decimal.TryParse方法。 And then you can use standard numeric format string "N2"然后您可以使用标准数字格式字符串“N2”

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

Your solution is just 2 steps away您的解决方案仅 2 步之遥

  • Parsing the user input to decimal format将用户输入解析为十进制格式
  • Then rounding off to 2 decimal places然后四舍五入到小数点后两位

.cs 。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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM