What is the Decimal.ToSingle() method in C#?
Overview
The Decimal.ToSingle() method converts a specified decimal value to its equivalent single-precision, floating-point number.
Syntax
public static float ToSingle (decimal d);
Parameters
d: This is the decimal number that we want to convert to a single-precision, floating-point number.
Return value
The value returned is a single-precision, floating-point number that is equivalent to the value of d given in the syntax above.
Code example
// use Systemusing System;// create classclass DecimalToSingle{// main methodstatic void Main(){// create decimaldecimal d1 = 34.222m;decimal d2 = 8.9999m;decimal d3 = -5.8m;// convert to Single// and print valueConsole.WriteLine("Value : {0}, type: {1}",Decimal.ToSingle(d1),Decimal.ToSingle(d1).GetType());Console.WriteLine("Value : {0}, type: {1}",Decimal.ToSingle(d2),Decimal.ToSingle(d2).GetType());Console.WriteLine("Value : {0}, type: {1}",Decimal.ToSingle(d3),Decimal.ToSingle(d2).GetType());}}
Code explanation
- Lines 10–12: We create some decimal variables,
d1,d2, andd3, and initialize them with decimal values. - Lines 16–24: We print the results of converting
d1,d2, andd3and the value that is returned. We also print the instance type by using theGetType()method.