แจก code c# เกี่ยวกับ decimal.Round

แนะนำ สอบถาม ภาษา C สำหรับผู้เริ่มต้น ภาษา Java ภาษา Python

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
jataz2
PHP Super Member
PHP Super Member
โพสต์: 275
ลงทะเบียนเมื่อ: 22/02/2011 11:48 am

แจก code c# เกี่ยวกับ decimal.Round

โพสต์ที่ยังไม่ได้อ่าน โดย jataz2 »

วิธีเรียกใช้งาน function
string display = FormatDecimalPlaces(ค่า deciaml, จำนวนจุดทศนิยมที่ต้องการ);
string display = FormatDecimalPlaces(31.02, 5);

ตัวอย่าง ต้องการทิศนิยม 5 ตำแหน่ง ถ้า input มีจุดทศนิยมเกิน 5 ก็ round ให้เหลือ 5 ตำแหน่ง

โค้ด: เลือกทั้งหมด

 /*            before -> after 
			   1) 31     -> 31.00000
			   2) 31.1   -> 31.10000
			   3) 31.01  -> 31.01000
			   4) 31.55571 -> 31.55571 
			   5) 31.555719-> 31.55572 
*/

โค้ด: เลือกทั้งหมด

public string FormatDecimalPlaces(decimal input, string decimalPlaces)
        {
            try
            {
                decimal tmp = input;

                //decimalPlaces = 2 -> patternSharp -> "0.##"     , patternDot -> .00
                //decimalPlaces = 5 -> patternSharp -> "0.#####"  , patternDot -> .00000
                int decP = 6;
                try
                {
                    decP = Convert.ToInt32(decimalPlaces);
                }
                catch
                {
                    decP = 6;
                }
                string patternSharp = "0.";
                string patternDot = ".";
                for (int j = 0; j < decP; j++)
                {
                    patternSharp += "#";
                    patternDot += "0";
                }

                if (tmp.ToString("0.######").IndexOf(".") > -1)
                {
                    //แสดงว่ามีจุดทศนิยม
                    string a = tmp.ToString("0.######").Split('.')[0];
                    string b = tmp.ToString("0.######").Split('.')[1];

                    if (b.Length > decP)
                    {
                        // 5)
                        return Decimal.Round(input, decP).ToString(patternSharp);
                    }
                    else if (b.Length == decP)
                    {
                        // 4)
                        return input.ToString(patternSharp);
                    }
                    else if (b.Length < decP)
                    {
                        // 2)  3)
                        return a + "." + b.PadRight(decP, '0');
                    }
                    else
                    {
                        return input.ToString(patternSharp) + patternDot;
                    }
                }
                else
                {
                    // 1)
                    return input.ToString(patternSharp) + patternDot;
                }
            }
            catch
            {
                return input.ToString("0.######");
            }
      }
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 3