字符串的转换

gauzeapricot122 2011-04-13 01:09:29
‘1/4’我要把前面那个分数转换为Decimal类型的 同时也适用(‘1’)整数类型转换为Decimal类型

这里的1/4 和1指的是字符串类型 而不是int类型
Convert.ToDecimal这个转换出错 提示信息:输入字符串的格式不正确 我想应该是出在1/4这个字符串上
...全文
83 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
kingdom_0 2011-04-13
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 bloodish 的回复:]

C# code

decimal val = (decimal)Convert.ChangeType((new DataTable()).Compute("1/4", string.Empty), typeof(decimal));
[/Quote]
学习了。
  • 打赏
  • 举报
回复
new DataTable()).Compute("1/4")
去查查这个的用法,你的字符串将参与运算,可以try一下
bloodish 2011-04-13
  • 打赏
  • 举报
回复

decimal val = (decimal)Convert.ChangeType((new DataTable()).Compute("1/4", string.Empty), typeof(decimal));
ColinMelody 2011-04-13
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 gauzeapricot122 的回复:]
引用 4 楼 matrixcl 的回复:
C# code

static void Main(string[] args)
{
string temp = "1/4";
string[] arr = temp.Split('/');
decimal result = 0;
if (arr.Lengt……
好办法 我是想找个快捷的方法嘛
[/Quote]
wangwang1103 2011-04-13
  • 打赏
  • 举报
回复
string[] arr = temp.Split('/');
decimal result;
if arr.leng >=2
result = decimal.Parse(arr[0]) / decimal.Parse(arr[1]);
else
result = decimal.Parse(arr[0]);
Console.WriteLine(result);
gauzeapricot122 2011-04-13
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 matrixcl 的回复:]
C# code

static void Main(string[] args)
{
string temp = "1/4";
string[] arr = temp.Split('/');
decimal result = 0;
if (arr.Lengt……
[/Quote]好办法 我是想找个快捷的方法嘛
gauzeapricot122 2011-04-13
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 beckfun 的回复:]
没看懂你的意思!!!
[/Quote]

就是我要把字符串转换为decimal类型
当字符串中出现了1/4这样的字符串
运行到转换1/4那行的时候报输入字符串的格式不正确的错误
懂了吧
lyl_lemon 2011-04-13
  • 打赏
  • 举报
回复
string[] str = "1/4".Split('/');
decimal result = decimal.Parse(str[0]) / decimal.Parse(str[1]);
q287551219 2011-04-13
  • 打赏
  • 举报
回复
我服了,你按上面的方法写个函数就得了,这都要别人帮你写?
matrixcl 2011-04-13
  • 打赏
  • 举报
回复

static void Main(string[] args)
{
string temp = "1/4";
string[] arr = temp.Split('/');
decimal result = 0;
if (arr.Length > 1)
{
result = decimal.Parse(arr[0]) / decimal.Parse(arr[1]);
}
else if (arr.Length == 1)
{
result = decimal.Parse(arr[0]);
}
else
{
throw new System.Exception();
}
Console.WriteLine(result);
}
beckfun 2011-04-13
  • 打赏
  • 举报
回复
没看懂你的意思!!!
gauzeapricot122 2011-04-13
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 q287551219 的回复:]
static void Main(string[] args)
{
string temp = "1/4";
string[] arr = temp.Split('/');
decimal result = decimal.Parse(arr[0]) / decimal.Parse(arr[1]);
Console.WriteLine(result);
}
[/Quote]呃。。。。 你这个好像就是专门针对‘1/4’这样的数据类型做操作了 那对于整数的还有用么
q287551219 2011-04-13
  • 打赏
  • 举报
回复
static void Main(string[] args)
{
string temp = "1/4";
string[] arr = temp.Split('/');
decimal result = decimal.Parse(arr[0]) / decimal.Parse(arr[1]);
Console.WriteLine(result);
}

110,566

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧