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

问题描述

TimeSpan ts;
Single nomonths;
ts=startDate.Substract(endDate);
nomonths = Convert.toSingle(ts.days/30);  //ts.days=57



因此,在nomonths中必须获得1.9,但显示为1

请帮助我.



So in nomonths has to get 1.9 but it is showing 1

Please help me.

推荐答案

double nomonths = Convert.TotalDays / 30d;



正确阅读System.TimeSpan帮助( http://msdn.microsoft.com/en-us/library /system.timespan.aspx [ ^ ]).不以总计"为前缀的属性返回整数值,但您需要浮点数.

您的问题是:将整数除以整数就可以将整数值转换为单值.甚至在调用Convert函数之前就切掉了小数部分(这完全是多余的).

—SA



Read System.TimeSpan help properly (http://msdn.microsoft.com/en-us/library/system.timespan.aspx[^]). Properties not prefixed with "Total" return integer value, but you need floating point.

Your problem was: division integer by integer gives you integer value converted to single. The fractional part was cut even before calling Convert function (which is totally redundant).

—SA


using System;
namespace ReadChapterOneOfAnyNETBook
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime startDate = DateTime.Now.AddDays(-57d);
            DateTime endDate = DateTime.Now;
            TimeSpan ts = endDate - startDate;
            float numberOfMonths = (float) ts.TotalDays / 30f;
            Console.WriteLine(numberOfMonths);
            Console.ReadKey();
        }
    }
}


这篇关于在csharp中转换的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:41