将字符串分数转换为十进制 [英] Convert String Fraction to Decimal

查看:122
本文介绍了将字符串分数转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



正在寻找将10 / 10.00转换为十进制的方式。

解决方案

< blockquote>

  public   static  十进制 FractionToDouble(字符串分数)
{
十进制结果;

if decimal .TryParse(fraction, out 结果))
{
return 结果;
}

string [] split = fraction.Split( new char [] {' '' /'});

if (split.Length == 2 || split.Length = = 3
{
decimal a,b;

if decimal .TryParse(split [ 0 ], out a)&&& decimal .TryParse( split [ 1 ], out b))
{
if (split.Length == 2
{
return decimal )b / a;
}

int c;

if int .TryParse(split [ 2 ], out c))
{
return a +( decimal )b / c;
}
}
}

throw new FormatException( 不是有效的分数。);
}
public static int ReadAllBytesFromStream(Stream stream, byte [] buffer)
{
// 使用此方法用于读取流中的所有字节。
int offset = 0 ;
int totalCount = 0 ;
while true
{
int bytesRead = stream.Read(buffer,offset, 100 );
if (bytesRead == 0
{
断裂;
}
offset + = bytesRead;
totalCount + = bytesRead;
}
return totalCount;
}


Hello,

looking for a way to convert "10/10.00" to decimal.

解决方案

public static decimal FractionToDouble(string fraction)
       {
           decimal result;

           if (decimal.TryParse(fraction, out result))
           {
               return result;
           }

           string[] split = fraction.Split(new char[] { ' ', '/' });

           if (split.Length == 2 || split.Length == 3)
           {
               decimal a, b;

               if (decimal.TryParse(split[0], out a) && decimal.TryParse(split[1], out b))
               {
                   if (split.Length == 2)
                   {
                       return (decimal)b / a;
                   }

                   int c;

                   if (int.TryParse(split[2], out c))
                   {
                       return a + (decimal)b / c;
                   }
               }
           }

           throw new FormatException("Not a valid fraction.");
       }
       public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
       {
           // Use this method is used to read all bytes from a stream.
           int offset = 0;
           int totalCount = 0;
           while (true)
           {
               int bytesRead = stream.Read(buffer, offset, 100);
               if (bytesRead == 0)
               {
                   break;
               }
               offset += bytesRead;
               totalCount += bytesRead;
           }
           return totalCount;
       }


这篇关于将字符串分数转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆