Add/remove 到小数点的大小号

Add/remove to decimal places for greater and smaller sign

我想将 string 值转换为 decimal。当有更小或更大的符号时,我想 add/remove 到这样的值

string value  |  decimal result
--------------|----------------
 "< 0.22"     |   0.219
 "< 32.45"    |   32.449
 "> 2.0"      |   2.01
 "> 5"        |   5.1

这必须适用于具有任意小数位数的十进制数。有没有一种优雅的方法可以做到这一点?

只能想到数小数位数,求最后一位,adding/removing ...

所以我会想象以下解决方案

  1. 拆分 space
  2. 上的字符串
  3. 识别标志(GT 或 LT)
  4. 计算小数位数并存储该值
  5. 将数字转换为小数
  6. 根据符号加或减 10^(-1 * (numberOfDecimals + 1))

不计算小数的解法:

如果字符串以>开头,追加"1"。如果字符串以 < 开头,则将最后一个字符替换为下一个较低的字符(注意:对于 "0"->"9" 并在其左侧的字符上重复)然后附加 "9". 然后在空白和Double.Parse右侧拆分。

无需计算数字或拆分小数...(您可以在 linqpad 中运行)

string inputString = "> 0.22";

string[] data = inputString.Split(' ');
double input = double.Parse(data[1]);
double gt = double.Parse(data[1] + (data[1].Contains('.') ? "1" : ".1"));

switch(data[0])
{
    case ">":
        gt.Dump(); // return gt;
        break;
    case "<":
        double lt = input - (gt - input);
        lt.Dump(); // return lt;
        break;
}

// you could even make it smaller by just doing (instead of the switch):
return data[0]==">" ? gt : input - (gt - input);

如果尾随零被允许作为输入但被认为是微不足道的,那么 trim 它们。

inputString = inputString.TrimEnd("0");

使用正则表达式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] inputs = {
                "< 0.22",
                "< 32.45",
                 "> 2.0"
                             };
            string pattern = @"(?'sign'[\<\>])\s+(?'integer'\d+).(?'fraction'\d+)";

            decimal number = 0;
            foreach(string input in inputs)
            {
                Match match = Regex.Match(input, pattern);
                if(match.Groups["sign"].Value == ">")
                {
                   number = decimal.Parse(match.Groups["integer"].Value  + "." + match.Groups["fraction"].Value);
                   number += decimal.Parse("." + new string('0', match.Groups["fraction"].Value.Length) + "1");
                }
                else
                {
                   number = decimal.Parse(match.Groups["integer"].Value  + "." + match.Groups["fraction"].Value);
                   number -= decimal.Parse("." + new string('0', match.Groups["fraction"].Value.Length) + "1");
                }

                    Console.WriteLine(number.ToString());
            }
            Console.ReadLine();

        }
    }
}