你能绕一个.NET TimeSpan对象吗? [英] Can you round a .NET TimeSpan object?

查看:129
本文介绍了你能绕一个.NET TimeSpan对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以绕一个.NET TimeSpan 对象吗?



我有一个 Timespan 的值为:00:00:00.6193789



有没有一个简单的方法来保持一个 TimeSpan 对象,但是它可以像

00:00:00.62?

解决方案

对不起,但是 这个问题和流行答案到目前为止是错误的: - )



问题是错误的因为Tyndall要求通过 回滚 ,而是显示一个 截断 的示例。

$ b $ (我想有人可以争辩答案是正确的两个问题之一,但让我们暂时忽略哲学...)



这是一个简单的技术

  int precision = 2; //指定小数点后的数字数量
TimeSpan t1 = new TimeSpan(19365678); // sample input value

const int TIMESPAN_SIZE = 7; //它总是有七位数
//将digitsToShow转换成四舍五入/截断蒙版
int factor =(int)Math.Pow(10,(TIMESPAN_SIZE - precision));

Console.WriteLine(Input:+ t1);
TimeSpan truncatedTimeSpan = new TimeSpan(t1.Ticks - (t1.Ticks%factor));
Console.WriteLine(截断:+ truncatedTimeSpan);
TimeSpan roundedTimeSpan =
new TimeSpan(((long)Math.Round((1.0 * t1.Ticks / factor))* factor));
Console.WriteLine(Rounded:+ roundedTimeSpan);

使用示例代码中的输入值和位数,这是输出:

 输入:00:00:01.9365678 
截断:00:00:01.9300000
圆角:00:00:01.9400000

将精度从2位数更改为5位数,取而代之:

 输入:00:00:01.9365678 
截断:00:00:01.9365600
四舍五入:00:00:01.9365700

甚至将其更改为0可获得此结果:

 输入:00:00:01.9365678 
截断:00:00:01
舍入:00:00:02

最后,如果您只想对输出进行更多的控制,请添加一些格式。这里有一个例子,表明您可以将精度与显示数字的数目分开。精度再次设置为2,但是如格式化控制字符串的最后一个参数所示,显示3位数字:

 控制台.WriteLine(Rounded / formatted:+ 
string.Format({0:00}:{1:00}:{2:00}。{3:000},
roundedTimeSpan。小时,roundedTimeSpan.Minutes,
roundedTimeSpan.Seconds,roundedTimeSpan.Milliseconds));
//输入:00:00:01.9365678
//截断:00:00:01.9300000
//舍入:00:00:01.9400000
//舍入/格式化:00 :00:01.940






2010.01.06更新:开箱即用的解决方案



如果您正在寻找想法,上述材料很有用;我已经有时间为那些寻找即用型代码的人实施打包解决方案。



请注意,这是未注释的代码。具有XML-doc-comments的完整注释版本将在本季度末在我的开源库中使用。虽然我犹豫着把这个原始的贴出来,但我认为对感兴趣的读者来说,这仍然可能是有益的。



这段代码改进了我的上面的代码,虽然圆润,仍然显示7个地方,用零填充。这个完成的版本回合并修剪到指定的位数。



这是一个示例调用:

  Console.Write(new RoundedTimeSpan(19365678,2).ToString()); 
// Result = 00:00:01.94

这里是完整的RoundedTimeSpan.cs文件:

  using System; 

命名空间CleanCode.Data
{
public struct RoundedTimeSpan
{

private const int TIMESPAN_SIZE = 7; //它总是有七位数

private TimeSpan roundedTimeSpan;
私有int精度;

public RoundedTimeSpan(long ticks,int precision)
{
if(precision< 0){throw new ArgumentException(precision must be non-negative); }
this.precision = precision;
int factor =(int)System.Math.Pow(10,(TIMESPAN_SIZE - precision));

//这只适用于舍入毫秒 - 将不会以秒/分钟/小时的速度工作!
roundedTimeSpan = new TimeSpan(((long)System.Math.Round((1.0 * ticks / factor))* factor));
}

public TimeSpan TimeSpan {get {return roundedTimeSpan; }}

public override string ToString()
{
return ToString(precision);
}

public string ToString(int length)
{//此方法修订2010.01.31
int digitsToStrip = TIMESPAN_SIZE - length;
string s = roundedTimeSpan.ToString();
if(!s.Contains(。)&& length == 0){return s; }
if(!s.Contains(。)){s + =。 +新字符串('0',TIMESPAN_SIZE); }
int subLength = s.Length - digitsToStrip;
return subLength< 0? :subLength>长度? s:s.Substring(0,subLength);
}
}
}






2010.02.01更新:现在可用的打包解决方案



我刚刚发布了一个新版本的我的开源库,比预期的要早,包括RoundedTimeSpan我上面描述过代码是 here ;对于API,请此处,然后导航到 RoundedTimeSpan CleanCode.Data 命名空间下。 CleanCode.DLL库包括上面显示的代码,但是在一个完整的包中提供。请注意,自从我在2010.01.06发布以来,我已经对 ToString(int)方法进行了一些改进。


Can you round a .NET TimeSpan object?

I have a Timespan value of: 00:00:00.6193789

Is there a simple way to keep it a TimeSpan object but round it to something like
00:00:00.62?

解决方案

Sorry, guys, but both the question and the popular answer so far are wrong :-)

The question is wrong because Tyndall asks for a way to round but shows an example of truncation.

Will Dean's answer is wrong because it also addresses truncation rather than rounding. (I suppose one could argue the answer is right for one of the two questions, but let's leave philosophy aside for the moment...)

Here is a simple technique for rounding:

int precision = 2; // Specify how many digits past the decimal point
TimeSpan t1 = new TimeSpan(19365678); // sample input value

const int TIMESPAN_SIZE = 7; // it always has seven digits
// convert the digitsToShow into a rounding/truncating mask
int factor = (int)Math.Pow(10,(TIMESPAN_SIZE - precision));

Console.WriteLine("Input: " + t1);
TimeSpan truncatedTimeSpan = new TimeSpan(t1.Ticks - (t1.Ticks % factor));
Console.WriteLine("Truncated: " + truncatedTimeSpan);
TimeSpan roundedTimeSpan =
    new TimeSpan(((long)Math.Round((1.0*t1.Ticks/factor))*factor));
Console.WriteLine("Rounded: " + roundedTimeSpan);

With the input value and number of digits in the sample code, this is the output:

Input: 00:00:01.9365678
Truncated: 00:00:01.9300000
Rounded: 00:00:01.9400000

Change the precision from 2 digits to 5 digits and get this instead:

Input: 00:00:01.9365678
Truncated: 00:00:01.9365600
Rounded: 00:00:01.9365700

And even change it to 0 to get this result:

Input: 00:00:01.9365678
Truncated: 00:00:01
Rounded: 00:00:02

Finally, if you want just a bit more control over the output, add some formatting. Here is one example, showing that you can separate the precision from the number of displayed digits. The precision is again set to 2 but 3 digits are displayed, as specified in the last argument of the formatting control string:

Console.WriteLine("Rounded/formatted: " + 
  string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
      roundedTimeSpan.Hours, roundedTimeSpan.Minutes,
      roundedTimeSpan.Seconds, roundedTimeSpan.Milliseconds));
// Input: 00:00:01.9365678
// Truncated: 00:00:01.9300000
// Rounded: 00:00:01.9400000
// Rounded/formatted: 00:00:01.940


2010.01.06 UPDATE: An Out-of-the-box Solution

The above material is useful if you are looking for ideas; I have since had time to implement a packaged solution for those looking for ready-to-use code.

Note that this is uncommented code. The fully commented version with XML-doc-comments will be available in my open source library by the end of the quarter. Though I hesitated to post it "raw" like this, I figure that it could still be of some benefit to interested readers.

This code improves upon my code above which, though it rounded, still showed 7 places, padded with zeroes. This finished version rounds and trims to the specified number of digits.

Here is a sample invocation:

Console.Write(new RoundedTimeSpan(19365678, 2).ToString());
// Result = 00:00:01.94

And here is the complete RoundedTimeSpan.cs file:

using System;

namespace CleanCode.Data
{
    public struct RoundedTimeSpan
    {

        private const int TIMESPAN_SIZE = 7; // it always has seven digits

        private TimeSpan roundedTimeSpan;
        private int precision;

        public RoundedTimeSpan(long ticks, int precision)
        {
            if (precision < 0) { throw new ArgumentException("precision must be non-negative"); }
            this.precision = precision;
            int factor = (int)System.Math.Pow(10, (TIMESPAN_SIZE - precision));

            // This is only valid for rounding milliseconds-will *not* work on secs/mins/hrs!
            roundedTimeSpan = new TimeSpan(((long)System.Math.Round((1.0 * ticks / factor)) * factor));
        }

        public TimeSpan TimeSpan { get { return roundedTimeSpan; } }

        public override string ToString()
        {
            return ToString(precision);
        }

        public string ToString(int length)
        { // this method revised 2010.01.31
            int digitsToStrip = TIMESPAN_SIZE - length;
            string s = roundedTimeSpan.ToString();
            if (!s.Contains(".") && length == 0) { return s; }
            if (!s.Contains(".")) { s += "." + new string('0', TIMESPAN_SIZE); }
            int subLength = s.Length - digitsToStrip;
            return subLength < 0 ? "" : subLength > s.Length ? s : s.Substring(0, subLength);
        }
    }
}


2010.02.01 UPDATE: Packaged solution now available

I just released a new version of my open-source libraries yesterday, sooner than anticipated, including the RoundedTimeSpan I described above. Code is here; for the API start here then navigate to RoundedTimeSpan under the CleanCode.Data namespace. The CleanCode.DLL library includes the code shown above but provides it in a finished package. Note that I have made a slight improvement in the ToString(int) method above since I posted it on 2010.01.06.

这篇关于你能绕一个.NET TimeSpan对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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