Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide not returning the decimal value I expect [duplicate]

Tags:

c#

math

Possible Duplicate:
What's wrong with this division?

If you divide 2 / 3, it should return 0.66666666666666667. Instead, I get 0.0 in double value type and 0 in decimal.

My purpose is to divide even (e.g. 2 / 3) and round to 1 always to the nearest.

Any help?

like image 563
George Taskos Avatar asked Apr 08 '10 01:04

George Taskos


People also ask

How do you divide numbers with decimals in Java?

BigDecimal bdec = new BigDecimal("706"); BigDecimal bdecRes = bdec. divide(new BigDecimal("20")); System. out. println("Divide: " + bdecRes); // Divide with MathContext MathContext mc = new MathContext(2, RoundingMode.

How do you divide long value?

Java Long divideUnsigned() Method. The divideUnsigned() method of Java Long class is used to return the unsigned quotient by dividing the first argument with the second argument such that each argument and the result is treated as an unsigned argument.


2 Answers

You're doing integer division, from the sounds of it. Try this:

decimal result = 2.0 / 3.0;

Or even force it to decimals for all of the operations:

decimal result = 2.0m / 3.0m;

This should give you a result more like you expect.

like image 77
Reed Copsey Avatar answered Oct 08 '22 00:10

Reed Copsey


Doing 2/3 is integer division which will not return the decimal place of the division. To get .666666667 you will need to do 2.0 / 3.0 which are both doubles to get the expected answer.

like image 8
msarchet Avatar answered Oct 07 '22 22:10

msarchet