[英]How do i convert a floating point string to an int in c#
我有一個字符串:
字符串測試=“ 19,95”;
並且我不想將其轉換為int。
我用:
int num = Convert.Int32(測試);
但是,它將引發FormatException。 並告訴我該字符串不是正確的轉換字符串。
我的猜測是它與十進制分隔符有關。
我該如何解決?
using System.Globalization;
...
NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ",";
double num = Convert.ToDouble(test, (IFormatProvider)nfi);
經過測試和工作。
為了完整性:
int applesApplesApples = Math.Ceiling(num);
int bananaBananaBanana = (int)num;
int cucumberCucumberCucumber = Math.Floor(num);
[更新]
正如Rushyo在下面的評論中正確指出的那樣,該示例是人為設計的,最佳實踐方法是確定要使用的文化,以便使用正確的CultureInfo對象。
然后,在執行所有數字格式設置時,可以使用該特定CultureInfo中的本地化NumberFormatInfo。
string dblText = "19,95";
CultureInfo ci = new CultureInfo ("en-US", true);
ci.NumberFormat.NumberDecimalSeparator = ",";
double dblValue = double.Parse (dblText, NumberStyles.AllowDecimalPoint, ci);
如果需要19(舍去小數部分):
int intValue = (int)dblValue;
如果需要20(數學舍入):
int intValue = (int)(dblValue + 0.5);
您期望從"19,95"
得到什么整數? 1995年? 19? 20嗎
也許您應該先將數字轉換為雙精度,然后再對應用程序有意義的任何方向四舍五入或截斷。
正如其他人已經提到的那樣,您問題的主要問題是,您沒有提供有關期望結果的任何信息,還有一些人也提出了Culture(十進制分隔符,千位分隔符)問題。 因此,我將作一點總結:
private int Parse(string text)
{
Decimal value;
//Select the culture you like to use
var culture = CultureInfo.CurrentCulture;
//var culture = CultureInfo.GetCultureInfo("en-US");
//var culture = CultureInfo.GetCultureInfo("de-DE");
if (Decimal.TryParse(text, NumberStyles.Number, culture, out value))
{
//Throw away the fractional part
//return (int)value;
//or make some rounding??
return (int)Math.Round(value, MidpointRounding.ToEven);
}
//What should happen if the parsing fails??
//Return some default value
return int.MinValue;
//return 0;
//Or throw an exception?
//throw new FormatException();
//In that case, maybe use directly Decimal.Parse and let this
//function throw the exception with the correct message.
}
您確定要成為一個int嗎?
這個數字是雙倍。
int num = (int)double.Parse(test); //will be 19
double num = double.Parse(test); //wil be 19.95
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.