The C double and decimal data types retain the specified number of decimal places as truncation

  • 2020-05-07 20:15:38
  • OfStack

In the project, it is used to take two decimal places by truncation, so the following method is written:
 
/// <summary> 
///  Truncate the numeric value by the specified number of decimal places  
/// </summary> 
/// <param name="d"> The decimal 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 a double - precision floating - point value by the specified number of decimal places  
/// </summary> 
/// <param name="d"> The double precision floating point number to truncate </param> 
/// <param name="s"> 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; 
} 

By the way, 1.
The ToString("#.##") methods of double and decimal use 4 rounding 5;
Round(decimal d, int decimals) under the static class System.Math, the rounding method USES "4 rounds 6 into 5 pairs";
The third parameter of Round(decimal d, int decimals, MidpointRounding mode) under Math is the enumeration parameter, indicating how to deal with the intermediate value (5);
The method of static class System. Math: http: / / msdn microsoft. com/zh - cn/library/system math_methods (v = vs. 80)

Related articles: