开发者

How to round to two decimal places in a string? [duplicate]

开发者 https://www.devze.com 2023-03-28 15:17 出处:网络
This question al开发者_运维技巧ready has answers here: Closed 10 years ago. Possible Duplicate: c# - How do I round a decimal value to 2 decimal places (for output on a page)
This question al开发者_运维技巧ready has answers here: Closed 10 years ago.

Possible Duplicate:

c# - How do I round a decimal value to 2 decimal places (for output on a page)

string strTemp = "0.51667308807373";

convert to decimal by rounding of two decimal places.


Math.Round(Convert.ToDecimal(strTemp), 2);


First convert string to decimal (Using Decimal.Parse or Decimal.TryParse).

decimal d = Decimal.Parse("123.45678");

Then round the decimal value using Round(d, m) where d is your number, m is the number of decimals, see http://msdn.microsoft.com/en-us/library/6be1edhb.aspx

decimal rounded = Decimal.Round(d, 2); 

If you only want to round for presentation, you can skip rounding to a decimal and instead simply round the value in output:

string.Format("{0:0.00}", 123.45678m);  


Convert the value to a floating point number, then round it:

double temp = Double.Parse(strTemp, CultureInfo.InvariantCulture);
temp = Math.Round(temp, 2);

Alternatively, if you want the result as a string, just parse it and format it to two decimal places:

double temp = Double.Parse(strTemp, CultureInfo.InvariantCulture);
string result = temp.ToString("N2", CultureInfo.InvariantCulture);

Note: The CultureInfo object is so that the methods will always use a period as decimal separator, regardless of the local culture settings.


var roundedTemp = Math.Round(decimal.Parse(strTemp), 2);

You might want to check to ensure the string is always a decimal first but think this is the essence of it.


you can use info from this link http://www.csharp-examples.net/string-format-double/ for the double value, use double.parse api


You can use Number format Info. Something like

NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;


double myInt = 0.51667308807373;

// Displays the same value with four decimal digits.
nfi.NumberDecimalDigits = 2;
Console.WriteLine(myInt.ToString("N", nfi));
Console.ReadKey();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号