C# float and double
In this chapter you will learn:
- C# float vs double types
- float point value literal: 3.281f and 5E-02
- Use Remainder Operator on float point data type
- floats and arithmetic operators
float vs double types
The floating-point types represent numbers with fractional components. There are two kinds of floating-point types:
float
,which represent single-precision numbersdouble
, which represent double-precision numbers.
The type float is 32 bits wide and has a range of 1.5E-45
to 3.4E+38
.
The double type is 64 bits wide and has a range of 5E-324
to 1.7E+308
.
float and double literal
using System;// ww w . j a va 2s.co m
class MainClass
{
static void Main(string[] args)
{
float MyFloat = 3.281f;
double MyDouble = 5E-02;
}
}
The following code shows how to use float literals.
using System;/* w w w . ja va2 s.c o m*/
using System.Globalization;
public class Example
{
public static void Main()
{
float number;
number = 1.23456E20F;
Console.WriteLine(number.ToString());
number = 1.23456E2F;
Console.WriteLine(number.ToString());
number = -3.12345F;
Console.WriteLine(number.ToString());
number = -123456787654-07F;
Console.WriteLine(number.ToString());
number = .65432F;
Console.WriteLine(number.ToString());
number = .000000001F;
Console.WriteLine(number.ToString());
}
}
The code above generates the following result.
Example 1
using System;/*from w w w .ja v a2 s . c om*/
class MainClass
{
static void Main()
{
Console.WriteLine("0.0f % 1.3f is {0}", 0.0f % 1.3f);
Console.WriteLine("0.3f % 1.3f is {0}", 0.3f % 1.3f);
Console.WriteLine("1.0f % 1.3f is {0}", 1.0f % 1.3f);
Console.WriteLine("1.3f % 1.3f is {0}", 1.3f % 1.3f);
Console.WriteLine("2.0f % 1.3f is {0}", 2.0f % 1.3f);
Console.WriteLine("2.3f % 1.3f is {0}", 2.3f % 1.3f);
}
}
The code above generates the following result.
Example 2
class MainClass/*w w w . j a v a 2 s .c o m*/
{
public static void Main()
{
System.Console.WriteLine("10f / 3f = " + 10f / 3f);
float floatValue1 = 10f;
float floatValue2 = 3f;
System.Console.WriteLine("floatValue1 / floatValue2 = " +
floatValue1 / floatValue2);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: