Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to divide decimals without implicit round up

In c# when you perform the division of two decimals the last digit of the result will automatically be rounded if the true mathematical result cannot be exactly stored as a decimal type.

I want to write a function that performs the division where the last digit is always rounded down even if the digit to the right of the last would normally cause a round up.

My function would be declared as MyDivide(decimal a, decimal b)

As an example MyDivide(2.0M, 3.0M) => 0.6666666666666666666666666666

whereas the c# division operator would yield 2.0M / 3.0M => 0.6666666666666666666666666667

Any help implementing this is appreciated.

like image 540
Andrew Best Avatar asked Dec 09 '10 05:12

Andrew Best


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C in C?

Full form of C is “COMPILE”. One thing which was missing in C language was further added to C++ that is 'the concept of CLASSES'. So ++ being the increment operator, C has an incremented version called as “C++”.

Why is CA procedural language?

C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.

Why is C language popular?

It is fast The programs that you write in C compile and execute much faster than those written in other languages. This is because it does not have garbage collection and other such additional processing overheads. Hence, the language is faster as compared to most other programming languages.


1 Answers

You're going to have to implement long division yourself. There is NO way to finagle the built-in division into doing this for you (hint: you can't distinguish between 2m / 3m and .6666666666666666666666666667m / 1m or 6666666666666666666666666667m / 10000000000000000000000000000m for that matter).

like image 165
jason Avatar answered Oct 05 '22 20:10

jason