deciaml percent = 0.123456789123456789M; //12345.ToString("p"); 生成 1,234,500.00% string q1 = percent.ToString("P"); //12.35%;自動四舍五入,百分數,千位分隔,自動兩個小數 string q2 = percent.ToString("P0"); //12%;P后邊跟數字,代表精度。 string q3 = percent.ToString("P1"); //12.3%; string q4 = percent.ToString("P2"); //12.35%; string q5 = percent.ToString("P3"); string q6 = percent.ToString("P4"); string q7 = percent.ToString("P5"); string q8 = percent.ToString("P6");
當然你還可以用一下方式:
decimal percent =0.24015M; string q9 = percent.ToString("0.##%"); //得到 "24.02%" //##個數表示保留的小數位數(必要時四舍五入)
以下為我寫的非四舍五入方法:
處理了0.03 要顯示為3% 的問題
#region 小數變百分比 /// <summary> /// 小數變百分比 /// </summary> /// <param name="temp">要轉化為百分比的原數字</param> /// <param name="length">小數點后有幾位數字</param> /// <returns></returns> public static string GetPercent(decimal Number) { int length = GetPointNumber(Number); if (length >= 2) { string temp = "P" + (length - 2).ToString(); return Number.ToString(temp); } else return ((int)(Number*100)).ToString() + "%"; } #endregion #region 獲取小數點后有幾位小數 public static int GetPointNumber(decimal Number) { var s = Number.ToString(); return s.Length - s.IndexOf('.') - 1; } #endregion
