C # double and decimal data types are truncated to retain the specified decimal places

Source: Internet
Author: User
Tags truncated

The project uses the truncation method to get the last two digits of the decimal point, so the following method is written: Copy codeThe Code is as follows: // <summary>
/// Truncates a small value by a specified decimal point
/// </Summary>
/// <Param name = "d"> decimals to be truncated </param>
/// <Param name = "s"> decimal places, s greater than or equal to 0, less than or equal to 28 </param>
/// <Returns> </returns>
Public static decimal ToFixed (decimal d, int s)
{
Decimal sp = Convert. ToDecimal (Math. Pow (10, s ));

If (d <0)
Return Math. Truncate (d) + Math. Ceiling (d-Math. Truncate (d) * sp)/sp;
Else
Return Math. Truncate (d) + Math. Floor (d-Math. Truncate (d) * sp)/sp;
}

/// <Summary>
/// Truncate the double-precision floating point value by the specified number of decimal places
/// </Summary>
/// <Param name = "d"> double-precision floating point number to be truncated </param>
/// <Param name = "s"> number of decimal places, s greater than or equal to 0, less than or equal to 15 </param>
/// <Returns> </returns>
Public static double ToFixed (double d, int s)
{
Double sp = Math. Pow (10, s );

If (d <0)
Return Math. Truncate (d) + Math. Ceiling (d-Math. Truncate (d) * sp)/sp;
Else
Return Math. Truncate (d) + Math. Floor (d-Math. Truncate (d) * sp)/sp;
}

The following is a reference:
The double and decimal ToString ("####") methods use rounding;
The Round (decimal d, int decimals) method under the static class System. Math. The rounding method is "four homes, six homes, five into two ";
The third parameter of the Round (decimal d, int decimals, MidpointRounding mode) in the static class System. Math is the enumeration parameter, indicating how to process the median (5 );
Static class System. Math method: http://msdn.microsoft.com/zh-cn/library/system.math_methods (v = vs.80)

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.