2012-08-22 45 views

Trả lời

7
var probablyDecimalString = "0.4351242134"; 
decimal value; 
if (Decimal.TryParse(probablyDecimalString , out value)) 
    Console.WriteLine (value.ToString("0.##")); 
else 
    Console.WriteLine ("not a Decimal"); 
+1

Thực ra nếu giá trị ban đầu là một chuỗi bạn cần Double.Parse đầu tiên. –

+0

Bạn đặc biệt cần phải phân tích cú pháp nếu bạn muốn đạt được làm tròn. – Zak

+0

xin lỗi, tôi đã từng thấy chuỗi chỉ trong ký hiệu báo giá. Lỗi của tôi. –

2
float f = float.Parse("0.4351242134"); 
Console.WriteLine(string.Format("{0:0.00}", f)); 

Xem this cho string.Format.

4
var d = decimal.Parse("0.4351242134"); 
Console.WriteLine(decimal.Round(d, 2)); 
+0

cảm ơn rất nhiều, hoạt động rất tốt –

4

Vâng, tôi sẽ làm gì:

var d = "0.4351242134"; 
Console.WriteLine(decimal.Parse(d).ToString("N2")); 
1

Sẽ trợ giúp này

double ValBefore= 0.4351242134; 
double ValAfter= Math.Round(ValBefore, 2, MidpointRounding.AwayFromZero); //Rounds"up" 
Các vấn đề liên quan