The rounding method in C # and the method for getting the timestamp (unixtime) in C #

Source: Internet
Author: User

If you ask C #ProgramClerk, how is the rounding method written. Many people can easily writeMath. Round () method. But I don't know what's sad!

Write the following calculation results:

Math. Round (0.5)
Math. Round (1.5)

Some may write, and the calculation result is1And2.

That's a big mistake! It turns out that the results of these two expressions are0And2! This is where many program bugs are located.

Careful programmers can take a look atMathDescription of the. Round (decimal) method. The return value is described as follows:

Return Value

Type: system. Decimal
The integer closest to parameter D.If the fractional part of D is in the middle of two integers, one of which is an even number and the other is an odd number, the return value is an even number.

ThisThe preceding two expressions return values 0 and 2, respectively. It also proves that the simple math. Round (decimal) method cannot implement the rounding function!

. Math. round () also provides some other overload methods, one of which is math. round (decimal, midpointrounding) method. This method can be used to rounding decimal places. The method is as follows:

Math. Round (decimal, midpointrounding. awayfromzero)

Success! Let our program say goodbye to bugs!

Certificate ------------------------------------------------------------------------------------------------------------------------------------------

. Net does not encapsulate the method for obtaining the timestamp (unixtime, relative to the number of milliseconds in the early morning of January 1, January 1, 1970. Therefore, I have written the following method for implementation.

Datetime starttime = timezone. currenttimezone. tolocaltime (NewSystem. datetime (1970,1,1,0,0,0,0));

Datetime nowtime = datetime. now;

LongUnixtime = (Long) Math. Round (nowtime-starttime). totalmilliseconds, midpointrounding. awayfromzero );

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.