มีวิธีง่ายๆ ใน c# ในการปัดเศษทศนิยมให้เป็นไตรมาสที่ใกล้ที่สุดหรือไม่ เช่น x.0, x.25, x.50 x.75 เช่น 0.21 จะปัดเศษเป็น 0.25, 5.03 จะปัดเศษเป็น 5.0
ขอบคุณล่วงหน้าสำหรับความช่วยเหลือใด ๆ
มีวิธีง่ายๆ ใน c# ในการปัดเศษทศนิยมให้เป็นไตรมาสที่ใกล้ที่สุดหรือไม่ เช่น x.0, x.25, x.50 x.75 เช่น 0.21 จะปัดเศษเป็น 0.25, 5.03 จะปัดเศษเป็น 5.0
ขอบคุณล่วงหน้าสำหรับความช่วยเหลือใด ๆ
หรือคุณสามารถใช้ UltimateRoundingFunction ที่ให้ไว้ในบล็อกนี้: http://rajputyh.blogspot.in/2014/09/the-ultimate-rounding-function.html
//amountToRound => input amount //nearestOf => .25 if round to quater, 0.01 for rounding to 1 cent, 1 for rounding to $1 //fairness => btween 0 to 0.9999999___. // 0 means floor and 0.99999... means ceiling. But for ceiling, I would recommend, Math.Ceiling // 0.5 = Standard Rounding function. It will round up the border case. i.e. 1.5 to 2 and not 1. // 0.4999999... non-standard rounding function. Where border case is rounded down. i.e. 1.5 to 1 and not 2. // 0.75 means first 75% values will be rounded down, rest 25% value will be rounded up. decimal UltimateRoundingFunction(decimal amountToRound, decimal nearstOf, decimal fairness) { return Math.Floor(amountToRound / nearstOf + fairness) * nearstOf; }
โทรด้านล่างสำหรับการปัดเศษมาตรฐาน เช่น 1.125 จะถูกปัดเศษเป็น 1.25
UltimateRoundingFunction(amountToRound, 0.25m, 0.5m);
โทรด้านล่างเพื่อปัดเศษค่าเส้นขอบลง เช่น 1.125 จะถูกปัดเศษเป็น 1.00
UltimateRoundingFunction(amountToRound, 0.25m, 0.4999999999999999m);
สิ่งที่เรียกว่า "การปัดเศษของ Banker" นั้นเป็นไปไม่ได้ด้วย UltimateRoundingFunction คุณต้องไปกับคำตอบของ paxdiablo สำหรับการสนับสนุนนั้น :)