开发者

Convert String to Int and precision loss

I've a little problem conver开发者_JAVA百科ting a string like "129.70" into an integer ( 12970 in this case). This is the function I wrote :

public static int valToInt(string v)
{
    int tmp = (int)(double.Parse(v, new System.Globalization.CultureInfo("en-US")) * 1000);
    return tmp / 10;
}

I did the *1000 and then /10 trick to solve such a problem, and it works well 99% of the times, but 129.70 seems to be a critical value, and is converted into 12969. Is there a way to do the conversion without any loss? Being money values, there will be no more than two decimal digits...


Why not strip the decimal place out of the string and then parse it?


public static int valToInt(string v)
{     
    return (int)(Decimal.Parse(v, new System.Globalization.CultureInfo("en-US")) * 100m);     
} 

Do you really need an "offset" int? Consider leaving the value as decimal.


I have read a great deal of commentary on 'why' integers and doubles are 'less precise' than decimals, but the short answer is to use decimals. For some references as to why:

  1. http://msdn.microsoft.com/en-us/library/364x0z75%28v=vs.80%29.aspx
  2. http://msdn.microsoft.com/en-us/library/yht2cx7b%28v=vs.80%29.aspx


Floating point values does inherently have precision limitations. Multiplying it by 1000 will not make it more precise, it simply can't represent the number exactly.

As you are truncating the number when converting it to int, you will exaggerate any precision losses. If the value is something like 129699.99999999 before converting it to int, you will just be chopping of the decimals and end up with 129699. That would also be possible to round to the correct value, but the integer division will chop off even more data, giving you 12969 instead of 12970.

Just multiply by 100, round, and convert to int:

public static int valToInt(string v) {
    return (int)Math.Round(Double.Parse(v, new System.Globalization.CultureInfo("en-US")) * 100.0);
}


try this its so simple...

public static int valToInt(string v)
{
    return int.Parse(v.Replace(".",""));
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜