C# 只有一位小数的字符串格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12146100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:16:10  来源:igfitidea点击:

String format for only one decimal place?

c#.net

提问by 4thSpace

I'd like to dispaly only one decimal place. I've tried the following:

我只想显示一位小数。我尝试了以下方法:

string thevalue = "6.33";
thevalue = string.Format("{0:0.#}", thevalue);

result: 6.33. But should be 6.3? Even 0.0 does not work. What am I doing wrong?

结果:6.33。但是应该是6.3吧?即使 0.0 也不起作用。我究竟做错了什么?

采纳答案by Ry-

You need it to be a floating-point value for that to work.

你需要它是一个浮点值才能工作。

double thevalue = 6.33;

Here's a demo.Right now, it's just a string, so it'll be inserted as-is. If you need to parse it, use double.Parseor double.TryParse. (Or float, or decimal.)

这是一个演示。现在,它只是一个字符串,因此将按原样插入。如果您需要解析它,请使用double.Parsedouble.TryParse。(或float,或decimal。)

回答by TheHe

option 1 (let it be string):

选项1(让它成为字符串):

string thevalue = "6.33";
thevalue = string.Format("{0}", thevalue.Substring(0, thevalue.length-1));

option 2 (convert it):

选项 2(转换它):

string thevalue = "6.33";
var thevalue = string.Format("{0:0.0}", double.Parse(theValue));

option 3 (fire up RegEx):

选项 3(启动 RegEx):

var regex = new Regex(@"(\d+\.\d)"); // but that everywhere, maybe static
thevalue = regexObj.Match(thevalue ).Groups[1].Value;

回答by Marcelo de Aguiar

ToString() simplifies the job. double.Parse(theValue).ToString("N1")

ToString() 简化了工作。 double.Parse(theValue).ToString("N1")

回答by PQubeTechnologies

Here are a few different examples to consider:

以下是一些需要考虑的不同示例:

double l_value = 6;
string result= string.Format("{0:0.00}", l_value );
Console.WriteLine(result);

Output : 6.00

输出:6.00

double l_value = 6.33333;
string result= string.Format("{0:0.00}", l_value );
Console.WriteLine(result);

Output : 6.33

输出:6.33

double l_value = 6.4567;
string result = string.Format("{0:0.00}", l_value);
Console.WriteLine(result);

Output : 6.46

输出:6.46

回答by hendrik

Here is another way to format floating point numbers as you need it:

这是另一种根据需要格式化浮点数的方法:

string.Format("{0:F1}",6.33);

回答by duc14s

Please this:

请这个:

String.Format("{0:0.0}", 123.4567); // return 123.5