sách gpt4 ăn đã đi

c# - IFormatProvider 从double到string的科学转换——位数

In lại 作者:太空狗 更新时间:2023-10-30 01:24:47 29 4
mua khóa gpt4 giày nike

我在从 double 到 string 的转换时遇到问题。

我要转换:

double value: 0.0772486324655191

string value: 0.0772486324655191

如果长度大于小数点后的 16 位数字,我希望它是这样的:

double value: 0.00063500244832493823

string value: 6.3500244832493823e-004

我尝试用 IFormatProvider 模式转换它:

0.0000000000000000e000

但是第一种情况的结果是

7.7248632465519100e-002

如何获取双向量中的位数?或者更好:我应该如何正确使用格式提供程序?

String specifier;
CultureInfo culture;
specifier = "0.0000000000000000e000";
culture = CultureInfo.CreateSpecificCulture("en-US");
Console.WriteLine(DoubleMirrored[0].ToString(specifier, CultureInfo.InvariantCulture));

câu trả lời hay nhất

为此,您肯定需要创建自定义格式化程序。

要创建自定义格式化程序,您应该了解以下内容:
string.Format 具有以下重载:string.Format(IFormatProvider, string, object[]),因此您必须创建一个 IFormatProvider,它将“提供”一个 ICustomFormatter,它将处理您的自定义格式。同一个类可以很容易地用于两个接口(interface)。

下面是一些完全符合您描述的代码:

public class DoubleFormatter : IFormatProvider, ICustomFormatter 
{
// Implementation of IFormatProvider:
public object GetFormat(Type t) {
if (t == typeof(ICustomFormatter)) {
return this;
}
trả về giá trị null;
}
// Implementation of ICustomFormatter:
public string Format(string format, object arg, IFormatProvider provider) {
// Search for the custom "EE" format specifier:
if (format == null || !format.StartsWith("EE")) return null;
format = format.Substring(2); // Trim "EE"
// Determine how many digits before we cutoff:
int digits;
if (!int.TryParse(format, out digits)) {
throw new FormatException("Format must contain digits");
}

// Get the value: (note, this will work for any numeric type)
var value = Convert.ToDouble(arg);
// Convert to string without using Exponential format:
var output = value.ToString("0."+(new string('#',digits)), provider);
// Determine how many digits are showing: (this part isn't culture-compatible)
var length = output.Length - output.IndexOf(".");
if (length <= digits) {
return output;
} khác {
return value.ToString("E"+format, provider);
}
}
}

下面是如何使用此代码的示例:

var tests = new[]{
0.0000055555,
0.00000555555555555555555,
};

var formatter = new DoubleFormatter();
foreach (var t in tests){
var result = string.Format(formatter, "{0:EE15}", t);
Console.WriteLine(result);
}

关于c# - IFormatProvider 从double到string的科学转换——位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8414873/

29 4 0
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress