Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding down to 2 decimal places in c#

How can I multiply two decimals and round the result down to 2 decimal places?

For example if the equation is 41.75 x 0.1 the result will be 4.175. If I do this in c# with decimals it will automatically round up to 4.18. I would like to round down to 4.17.

I tried using Math.Floor but it just rounds down to 4.00. Here is an example:

Math.Floor (41.75 * 0.1); 
like image 510
startupsmith Avatar asked Nov 23 '12 01:11

startupsmith


People also ask

What is 2f in C?

2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places.

How do you round off in C?

round() function in c is used to return the nearest integer value of the float/double/long double argument passed to this function. If the decimal value is from ". 1 to . 5", it returns an integer value which is less than the argument we passed and if the decimal value is from ".


2 Answers

The Math.Round(...) function has an Enum to tell it what rounding strategy to use. Unfortunately the two defined won't exactly fit your situation.

The two Midpoint Rounding modes are:

  1. AwayFromZero - When a number is halfway between two others, it is rounded toward the nearest number that is away from zero. (Aka, round up)
  2. ToEven - When a number is halfway between two others, it is rounded toward the nearest even number. (Will Favor .16 over .17, and .18 over .17)

What you want to use is Floor with some multiplication.

var output = Math.Floor((41.75 * 0.1) * 100) / 100; 

The output variable should have 4.17 in it now.

In fact you can also write a function to take a variable length as well:

public decimal RoundDown(decimal i, double decimalPlaces) {    var power = Convert.ToDecimal(Math.Pow(10, decimalPlaces));    return Math.Floor(i * power) / power; } 
like image 194
Aren Avatar answered Oct 09 '22 00:10

Aren


public double RoundDown(double number, int decimalPlaces) {      return Math.Floor(number * Math.Pow(10, decimalPlaces)) / Math.Pow(10, decimalPlaces); } 
like image 21
Wichukorn Dandecha Avatar answered Oct 09 '22 00:10

Wichukorn Dandecha