C#中的数据格式字符串 [英] Data format string in c#

查看:49
本文介绍了C#中的数据格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的C#代码做数据格式字符串功能.
string s = 0.98677;
此值直接来自数据库表,并将其捕获到字符串变量中.
我只希望输出0.98,然后使用数据格式字符串.
string str = (s,"0:0.##");

string.format("0:0.00",s)
但这不能给我确切的答案,最多2位数字0.98.
请为我解决这个问题.

问候,
Ravi

I want to do data format string function for my c# code.
string s = 0.98677;
this value come directlly from database table and catch it in string variable.
I want output only 0.98, then i use data format string.
string str = (s,"0:0.##");
or
string.format("0:0.00",s)
but this not give me exact answer upto 2 digit 0.98.
Please help me for my this problem.

regards,
Ravi

推荐答案

似乎您只想将小数点后一位而不是四舍五入即可.
我的意思是0.98677的0.98,而不是0.99.如果是这种情况,请使用以下功能
Seems like you just want first to decimals, not rounding.
I mean 0.98 for 0.98677, not 0.99. If it is the case, use following function
public string getValueUpto2Decimal(string value)
{
	if (value.Contains(".")) { 
		value += "00"; //to ensure that there are at least 2 digits after decimal point
	} else {
		value += ".00"; //place 00 after decimal
	}
	return value.Substring(0, value.IndexOf(".") + 3);
}



这完全基于字符串函数.

尽管我严重怀疑您是否从数据库中获得了字符串值.如果您从数据库中获得double,则只需使用ToString()将其传递给函数.



This is purely based on string functions.

Though I seriously have a doubt that you get a string value from database. If you get a double from database, then just use ToString() to pass it to the function.


这里是另一种解决方案

Here is one more solution

double   s = 0.93245;
           string s1= s.ToString("0.00");


我必须建议您
单击此处[^ ]
I must Suggest you to
Click Here [^]


这篇关于C#中的数据格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆