如何将字符串固定为双精度或双精度为字符串编码

时间:2019-02-04 20:23:58

标签: c# asp.net

我已经完成了代码,但是网页无法计算,除了计算之外,它无法执行其他所有操作。

protected void btnCompute_Click(object sender, EventArgs e)
{
    string gradebook,
        article,
        homework,
        practice,
        total;

    Double IndividualRate = .40,
        ArticleRate = .10,
        HomeworkRate = .25,
        PracticeRate = .25;

    string individualamt,
        articleamt,
        homeworkamt,
        practiceamt;

    gradebook = Convert.ToString(txtindividualproject.Text);
    homework = Convert.ToString(txtHomeworkAssignements.Text);
    article = Convert.ToString(txtArticleReview.Text);
    practice = Convert.ToString(txtPracticeAssignment.Text);

    individualamt = gradebook * IndividualRate;
    articleamt = article * ArticleRate;
    homeworkamt = homework * HomeworkRate;
    practiceamt = practice * PracticeRate;

    lbltotal.Text = individualamt + articleamt + homeworkamt + practiceamt;

    lbltotal.Visible = true;

我正在尝试计算总数。

2 个答案:

答案 0 :(得分:-1)

对不起,那是错误的代码...

受保护的无效btnCompute_Click(对象发送者,EventArgs e)     {         双重成绩册             文章,             家庭作业,             实践,             总计

        IndividualRate = .40,
        ArticleRate = .10,
        HomeworkRate = .25,
        PracticeRate = .25,
        individualamt ,
        articleamt,
        homeworkamt,
        practiceamt;

    gradebook = Convert.ToDouble(txtindividualproject.Text);
    homework = Convert.ToDouble(txtHomeworkAssignements.Text);
    article = Convert.ToDouble(txtArticleReview.Text);
    practice = Convert.ToDouble(txtPracticeAssignment.Text);


    individualamt = gradebook * IndividualRate;
    articleamt = article * ArticleRate;
    homeworkamt = homework * HomeworkRate;
    practiceamt = practice * PracticeRate;

    total = individualamt + articleamt + homeworkamt + practiceamt;

    lbltotal.Visible = true;
    lbltotal.Text = total.ToString("c");




}

答案 1 :(得分:-1)

@Joe,欢迎您使用Stack Overflow(SO)。

首先,当您应该使用Convert.ToDouble()时,您正在使用Convert.ToString()。但是,我也不能真正建议使用Convert.ToDouble()。

Convert.ToDouble()或System.Convert类中的任何方法的问题在于它不是异常安全的,这意味着它不处理异常。如果尝试Convert.ToDouble(“ a”),它将引发异常。如果该值不是数字,则不允许使用默认值。

所以有Double.TryParse。那更安全。

    if (!double.TryParse(txtindividualproject.Text, out gradebook)))
        // Do something on false

此时,代码变得丑陋且冗长。这就是为什么我创建了自己的字符串库:Rhyous.StringLibrary的原因。实际上,这里有大量的NuGet软件包只是为了简化字符串。许多人都有自己的字符串库或扩展名,因为他们反复在上面编写相同的代码,并且对此感到恼火。

您可以使用上面的代码,也可以使用Rhyous.StringLibrary NuGet package或直接在项目中使用类文件。这是一个链接。 https://github.com/rhyous/StringLibrary/blob/master/src/Rhyous.StringLibrary.Shared/Conversion/PrimitiveStringExtensions.cs

此外,由于SO喜欢发布的代码,而不仅仅是链接到的代码,因此它是:

using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace Rhyous.StringLibrary
{
    public static class PrimitiveStringExtensions
    {
        public static T To<T>(this string s, T defaultValue = default(T))
            where T : IComparable, IComparable<T>, IEquatable<T>
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
            try { return (T)converter.ConvertFromString(null, CultureInfo.InvariantCulture, s); }
            catch { return defaultValue; }
        }

        public static object ToType(this string s, Type type, object defaultValue = null)
        {
            MethodInfo mi = null;
            MethodInfo method = null;
            if (type.IsEnum)
            {
                mi = typeof(StringEnumExtensions).GetMethods().FirstOrDefault(m => m.Name == "ToEnum" && m.GetParameters().Length == 4);
                method = mi.MakeGenericMethod(type);
                var defaultEnum = Enum.GetValues(type).GetValue(0);
                return method.Invoke(null, new object[] { s, defaultEnum, true, true });
            }
            mi = typeof(PrimitiveStringExtensions).GetMethod("To");
            method = mi.MakeGenericMethod(type);
            // Check if it is DateTime to handle this critical .NET bug
            // https://connect.microsoft.com/VisualStudio/feedback/details/733995/datetime-default-parameter-value-throws-formatexception-at-runtime
            if (type == typeof(DateTime))
                defaultValue = DateTime.MinValue;
            return method.Invoke(null, new object[] { s, defaultValue ?? Type.Missing });
        }

        public static byte ToByte(this string s, byte defaultValue = 0)
        {
            return To(s, defaultValue);
        }

        public static bool ToBool(this string s, bool defaultValue = false)
        {
            return To(s, defaultValue);
        }

        public static DateTime ToDate(this string s, DateTime defaultValue = default(DateTime))
        {
            return To(s, defaultValue);
        }

        public static decimal ToDecimal(this string s, decimal defaultValue = 0.0M)
        {
            return To(s, defaultValue);
        }

        public static double ToDouble(this string s, double defaultValue = 0.0D)
        {
            return To(s, defaultValue);
        }

        public static float ToFloat(this string s, float defaultValue = 0.0F)
        {
            return To(s, defaultValue);
        }

        public static int ToInt(this string s, int defaultValue = 0)
        {
            return To(s, defaultValue);
        }

        public static long ToLong(this string s, long defaultValue = 0L)
        {
            return To(s, defaultValue);
        }

        public static sbyte ToSByte(this string s, sbyte defaultValue = 0)
        {
            return To(s, defaultValue);
        }

        public static short ToShort(this string s, short defaultValue = 0)
        {
            return To(s, defaultValue);
        }

        public static uint ToUint(this string s, uint defaultValue = 0U)
        {
            return To(s, defaultValue);
        }

        public static ulong ToULong(this string s, ulong defaultValue = 0UL)
        {
            return To(s, defaultValue);
        }

        public static ushort ToUShort(this string s, ushort defaultValue = 0)
        {
            return To(s, defaultValue);
        }

        public static Guid ToGuid(this string s, Guid defaultValue = default(Guid))
        {
            return To(s, defaultValue);
        }
    }
}

您将使用此类:

gradebook = txtindividualproject.Text.To<double>(0.0);
homework = txtHomeworkAssignements.Text.To(0.0);
article = txtArticleReview.Text.To(0.0);
practice = txtPracticeAssignment.Text.To<double>(0.0);

如您所见,从Rhyous.StringLibarary获得的代码处理异常,提供默认值,易于使用,简洁而不冗长且非常易读。