Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# แปลง Double เป็นค่าจำนวนเต็ม (Integer)


ภาพรวม

เพื่อแปลงค่า double เป็น int (Int32) ให้ใช้เมธอด Convert.ToInt32() ซึ่งจะ ปัดเศษทศนิยม ตามกฎ Banker's Rounding (ปัดเป็นเลขคู่เมื่ออยู่กึ่งกลาง)

รูปแบบการใช้งาน

double val = 21.34;
int res = Convert.ToInt32(val); // 21

ตัวอย่างโค้ดเต็ม

using System;

public class Demo
{
    public static void Main()
    {
        double val = 21.34;
        int res = Convert.ToInt32(val);
        Console.WriteLine("Converted double {0} to integer {1}", val, res);
    }
}

ผลลัพธ์

Converted double 21.34 to integer 21

เมธอดแปลงที่เกี่ยวข้อง

เมธอดพฤติกรรมตัวอย่าง 21.5ตัวอย่าง -21.5
Convert.ToInt32ปัด Banker's Rounding22-22
(int)val (cast)ตัดทศนิยม (truncate)21-21
Math.Roundปัดตามกฎที่ระบุ22 (default)-22
Math.Floorปัดลง21-22
Math.Ceilingปัดขึ้น22-21
Math.Truncateตัดทศนิยม21-21