如何将百分比字符串转换为双倍?

6

本文介绍了如何将百分比字符串转换为双倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个像1.5%"这样的字符串,想把它转换成双精度值.

I have a string like "1.5%" and want to convert it to double value.

可以通过以下方式简单地完成:

It can be done simple with following:

public static double FromPercentageString(this string value)
{
    return double.Parse(value.SubString(0, value.Length - 1)) / 100;
}

但我不想使用这种解析方式.

but I don't want to use this parsing approach.

还有其他方法可以使用 IFormatProvider 或类似的方法吗?

Is any other approach with IFormatProvider or something like this?

推荐答案

如果您关心捕获格式错误,我会使用 TrimEnd 而不是 Replace.替换将允许格式错误通过而不被发现.

If you care about catching formatting errors, I would use TrimEnd rather than Replace. Replace would allow formatting errors to pass undetected.

var num = decimal.Parse( value.TrimEnd( new char[] { '%', ' ' } ) ) / 100M;

这将确保该值必须是某个十进制数字,后跟任意数量的空格和百分号,即,它必须至少以正确格式的值开头.更准确地说,您可能希望在%"上进行拆分,而不是删除空条目,然后确保只有两个结果,第二个是空的.第一个应该是要转换的值.

This will ensure that the value must be some decimal number followed by any number of spaces and percent signs, i.e, it must at least start with a value in the proper format. To be more precise you might want to split on '%', not removing empty entries, then make sure that there are only two results and the second is empty. The first should be the value to convert.

var pieces = value.Split( '%' );
if (pieces.Length > 2  || !string.IsNullOrEmpty(pieces[1]))
{ 
    ... some error handling ... 
}
var num = decimal.Parse( pieces[0] ) / 100M;

使用 Replace 将允许您成功并错误地 IMO 解析以下内容:

Using Replace will allow you to successfully, and wrongfully IMO, parse things like:

  • %1.5
  • 1%.5
  • 1.%5

除了1.5%

这篇关于如何将百分比字符串转换为双倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

C# 中的多播委托奇怪行为?
Multicast delegate weird behavior in C#?(C# 中的多播委托奇怪行为?)...
2023-11-11 C#/.NET开发问题
6

参数计数与调用不匹配?
Parameter count mismatch with Invoke?(参数计数与调用不匹配?)...
2023-11-11 C#/.NET开发问题
26

如何将代表存储在列表中
How to store delegates in a List(如何将代表存储在列表中)...
2023-11-11 C#/.NET开发问题
6

代表如何工作(在后台)?
How delegates work (in the background)?(代表如何工作(在后台)?)...
2023-11-11 C#/.NET开发问题
5

没有 EndInvoke 的 C# 异步调用?
C# Asynchronous call without EndInvoke?(没有 EndInvoke 的 C# 异步调用?)...
2023-11-11 C#/.NET开发问题
2

Delegate.CreateDelegate() 和泛型:错误绑定到目标方法
Delegate.CreateDelegate() and generics: Error binding to target method(Delegate.CreateDelegate() 和泛型:错误绑定到目标方法)...
2023-11-11 C#/.NET开发问题
14