将文本分数转换为小数 [英] Convert a text fraction to a decimal

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

问题描述

类似于此问题,仅使用C#而不是JavaScript。我在搜索时找不到C#的任何内容

Similar to this question just in C# instead of JavaScript. I couldn't find anything for C# while searching

我有一个文本框,该文本框将容纳一个数量,该数量随后以双精度形式存储在数据库中。但是,有可能会将某些数量作为字符串分数输入,例如1/2表示0.5。
我希望能够将它们转换为十进制,然后再将它们存储到数据库中(也可以转换回十进制,但这很好,但这不是必需的)。我希望能够同时处理分数和带分数2 1/2被保存为2.5

I have a text box that will take a quantity, which is later stored as a double in a database. However it is possible that some quantities will be entered as string fractions e.g 1/2 for 0.5. I want to be able to convert these to decimal before storing them to the database (being able to also convert back would be nice but not necessary). I want to be able to handle both fractions and mixed numbers e.g. 2 1/2 is saved as 2.5

有人知道这样做的方法吗?

Anybody know a way of doing this?

推荐答案

尝试在空格和斜杠上将其拆分,例如:

Try splitting it on the space and slash, something like:

double FractionToDouble(string fraction) {
    double result;

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

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

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

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

            int c;

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

    throw new FormatException("Not a valid fraction.");
}

嘿,它起作用了!还记得检查是否除以零。结果将得到Infinity,-Infinity或NaN。

Hey, it worked! Remember to check for a division by zero, too. You'll get Infinity, -Infinity, or NaN as a result.

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

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