Funky
Funky

Reputation: 13612

C# - Data Type for value 0.5

I have a calculation for example 2/4 = 0.5, except I can't find a data type that will store this value! Every time I make the calculation it says 0.

Anyone have any suggestions?

Upvotes: 2

Views: 10454

Answers (5)

musefan
musefan

Reputation: 48415

Either float or double will do the job.

float x = 2f / 4f;
double x = 2d / 4d;

Note that you can specify constant values to be float or doubles by appending the appropriate character (f or d).

The important thing to remember is that the first data type (on the left) will determine the data type of the result. EDIT: actually, in this case either value being a float/double will work

So...

var x = 2 / 4;//x is int (0)
var x = 2f / 4;//x is float (0.5f)
var x 2d / 4;//x is double (0.5d)

C# will automatically convert int to float/double so...

float x = 2 / 4;//result type is int, but gets stored as convert float

Anyway, hope that helps explain some things

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500873

Either double or decimal will work fine.

However, if you just write:

// Wrong
double x = 2 / 4;

then it will still use integer division - because both of the operands for the division operator are of type int.

You can either cast either or both of the operands to double, or use a double literal for either or both of them:

// Any of these...
double x = (double) 2 / 4;
double x = 2 / (double) 4;
double x = (double) 2 / (double) 4;
double x = 2.0 / 4;
double x = 2 / 4.0;
double x = 2.0 / 4.0;
double x = 2d / 4;
double x = 2 / 4d;
double x = 2d / 4d;

Note that both double and decimal are floating point types. They don't represent arbitrary rational numbers (fractions). For example, neither can accurately represent 1/3. If you need a rational number type, you'll have to write your own or look for a third party implementation.

Upvotes: 12

J. Steen
J. Steen

Reputation: 15578

You can cast,

double value = (double)2/4;

or you can provide your input with decimals

double value = 2.0/4.0;

Upvotes: 1

Anders Abel
Anders Abel

Reputation: 69260

Use 2/4.0 to force it to use floating point arithmetics. Then you can store it in a double:

double d = 2/4.0;

If in the real code you have variables, cast the divisor to a double:

int i = 2;
int j = 4;
double d = i/(double)j;

Upvotes: 3

Teoman Soygul
Teoman Soygul

Reputation: 25742

Make sure at least one of the divisor or the dividend is a floating number:

double d = 2 / 4.0;
Console.WriteLine(d): // Writes: 0.5

Upvotes: 4

Related Questions