简体   繁体   中英

How can I convert fraction to double or decimal?

Case:

double x = Math.Pow(Convert.ToDouble(0.07003 + 1 ),(1/12));
Console.WriteLine(x);

Output:

1

The above output is incorrect, because the result of x is 1 instead of 1.005657

How to convert 1/12 in a format that it gives fractional value and is accepted by Math.Pow() .

And the real problem is division of 1 by 12 ( 1/12 ) which gives value 0 (instead of 0,083333... ).

Try this:

double x = Math.Pow(Convert.ToDouble(0.07003 + 1 ),(1/12d));

This makes 12 a double which makes the result of 1/12 a double. So instead of getting 0 from that division the result will be 0.0833333333333333 .

The literals 1 and 12 are both integers, so 1/12 is an integer division, giving an integer result (0). Change at least one literal to double or decimal to perform a floating point division.

To make a number literal a double , add decimal places (eg 1.0 ) or 'D' suffix ( 1D ). To make it a decimal, add 'M' suffix ( 1M ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM