如何在下面的scinerio中将double转换为int? [英] How to convert double into int in following scinerio?
问题描述
使用谷歌api我得到两个位置之间的距离。距离显示为(10km),当我试图按距离和速率获得成本时,出现错误[格式不正确]。
我使用的
代码,
双倍距离= convert.ToDouble(TextBox2.Text);
double rate = convert.ToDouble(TextBox1.Text);
int cost = distance * rate;
TextBox5.Text =Your Trip_Cost is+ cost;
谢谢
当你使用Convert时,它试图转换整个字符串变成一个数字。如果字符串包含字母字符,那么它将失败。
这有几种方法,但我可能使用正则表达式:
string input = 12km跨度>;
匹配m = Regex.Match(输入, @ (?< value> \d *( .\d +){0,1})(小于?规模> \w *)
跨度>);
if (m.Success)
{
double d = double .Parse(m.Groups [ value].Value);
string scale = m.Groups [ 尺度跨度>]值。
}
这允许用户输入浮点数和比例因子(在您的示例中为km),您可以检查并使用它将浮点数偏移到具有内部一致性的值。
因为它是一个文本框,所以你真的不应该依赖用户输入有效数据!
using google api i get distance between two location. The Distance shows like(10km),when i am trying to get cost according distance and rate , an error occured["incorrect format"].
code that i used,
double distance=convert.ToDouble(TextBox2.Text);
double rate=convert.ToDouble(TextBox1.Text);
int cost=distance*rate;
TextBox5.Text="Your Trip_Cost is"+cost;
Thanks
When you use Convert, it tries to convert the whole string into a number. If the string contains alpha characters, then it will fail.
There are a couple of ways round this, but I'd probably use a regex:
string input = "12km"; Match m = Regex.Match(input, @"(?<value>\d*(.\d+){0,1})(?<scale>\w*)
"); if (m.Success) { double d = double.Parse(m.Groups["value"].Value); string scale = m.Groups["scale"].Value; }
This allows the user to enter a floating point number, and a scale factor ("km" in your example) which you can check and use to "offset" the floating point number to a value that has internal consistency.
Since it's a textbox, you really shouldn't rely on the user entering valid data!
这篇关于如何在下面的scinerio中将double转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!