Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

C Sharp float: Difference between revisions

From Coderwiki
add: casting
m replace 'd' passed to float.Parse with 'c'
 
(One intermediate revision by the same user not shown)
Line 18: Line 18:


== Casting ==
== Casting ==
To [[Casting|cast]] to an '''int''', you can use the [[C Sharp casting|casting operator]] <code>(float)</code> for casting from numerical values, or the [[C Sharp float.Parse|float.Parse]] [[function]] for casting a [[String]] (see [[C Sharp string]]) to a <code>float</code>:<syntaxhighlight lang="cs" line="1">
To [[Casting|cast]] to a '''float''', you can use the [[C Sharp casting|casting operator]] <code>(float)</code> for casting from numerical values, or the [[C Sharp float.Parse|float.Parse]] [[function]] for casting a [[String]] (see [[C Sharp string]]) to a <code>float</code>:<syntaxhighlight lang="cs" line="1">
int a = 70;
int a = 70;
float b = (float)a; // 70.0
float b = (float)a; // 70.0
string c = "56.9";
string c = "56.9";
float d = float.Parse(d); // 56.9
float d = float.Parse(c); // 56.9
</syntaxhighlight>This is different to casting to a [[double]], which uses the <code>(double)</code> operator or the [[C Sharp double.Parse|double.Parse]] function.
</syntaxhighlight>This is different to casting to a [[double]], which uses the <code>(double)</code> operator or the [[C Sharp double.Parse|double.Parse]] function.

Latest revision as of 13:23, 19 August 2025

The float class in C Sharp is a data type which can store positive and negative decimal numbers in variables.

See Floating point for generic information about what floats can represent and how they are represented in memory.

A float in C# is represented by 4 bytes, or 32 bits.

They are usually accurate up to around 7 digits.

If you need more precision or larger/smaller numbers, you can instead use the double data type.

float a;
float b = 539.72;
float c = (float)781; // 781.0

To cast to a float, you can use the casting operator (float) for casting from numerical values, or the float.Parse function for casting a String (see C Sharp string) to a float:

int a = 70;
float b = (float)a; // 70.0
string c = "56.9";
float d = float.Parse(c); // 56.9

This is different to casting to a double, which uses the (double) operator or the double.Parse function.