Lorry Laurence mcLarry
Lorry Laurence mcLarry

Reputation: 394

C# How to convert between Float and Decimal?

I want to use a NumberUpDownBox to get and set a float value. All I Know is that this doesn't work:

DecimalConverter dec = new DecimalConverter();
((NumericUpDown)_control).Value = (Decimal)dec.ConvertFrom((float)value);

I am finding little documentation on how to do this...

Upvotes: 0

Views: 3567

Answers (2)

Paul Boddington
Paul Boddington

Reputation: 37645

One way is just to cast:

float a = 2.3F;
decimal d = (decimal)a;

Alternatively you could use a decimal constructor:

decimal d = new decimal(a);

Upvotes: 1

Brian Rogers
Brian Rogers

Reputation: 129697

The Convert class has static methods for converting between most primitive types.

To convert from float to decimal you can use Convert.ToDecimal():

float f = 1.0f;
decimal d = Convert.ToDecimal(f);

To go the other way you can use Convert.ToSingle():

decimal d = 1.0m;
float f = Convert.ToSingle(d);

Upvotes: 2

Related Questions