Skip to content

Converting between numeric types

Ziaw edited this page Nov 30, 2011 · 3 revisions

== Converting between numeric types ==

  • Category: Arithmetic
  • Description: This sample shows how to convert between various numeric types
  • Code:
using System;
using System.Console;

    def i1 = 3.1415 :> int;
    def i2 = 3.1415 :> long;
    WriteLine($"i1 = $i1, i2 = $i2");

    // Manipulating double precision floating point numbers
    def pi2 = 3 + 0.1415;   // there is implicit conversion to double
    def pi1 = pi2 :> float;   // ':>' is an overloaded explisit type conversion operator
    WriteLine($"pi1 = $pi1, pi2 = $pi2, pi3 = $pi3");
  
  
    // Manipulating single-precision (32-bit) floating point numbers
    def f32a = 2.1415f + 1.0f;        // float (System.Single)
    def f32b = 2.1415f + 1 : float;   // you can use type enforcment operator ":" 
    def f32c = 3  + 0.1415f;          // there is implicit conversion to float
    WriteLine($"f32a = $f32a, f32b = $f32b, f32c = $f32c");  
  
    // Manipulating bytes
    def byteA : byte = 3 + 4;       // byte 
    def byteB = 255u  : byte;       // byte 
    def byteC = 0xFFu : byte;       // byte 
    def byteD = 0xFF  : byte;       // byte 
    def byteE = 42b;                // byte 
    WriteLine($"byteA = $byteA, byteB = $byteB");    
  • Execution Result:
i1 = 3, i2 = 3
pi1 = 3.1415, pi2 = 3.1415
f32a = 3.1415, f32b = 3.1415
byteA = 7, byteB = 255

  • Copyright Samples used from "F# 3.0 Sample Pack" ([http://fsharp3sample.codeplex.com/]) at Codeplex OpenSource Community for non-commercial usage. All copyrights and authorship on materials this publication based on, is belongs to Microsoft corp. Copyright © 2006-2011 Microsoft Corporation, . All rights reserved. Copyright and autorship for materials in Nemerle language belongs to Nemerle Project Team. Copyright © 2008-2011 Nemerle Project Team. All rights reserved.
Clone this wiki locally