如果字符串必须满足长度要求,如何转换字符串中的双精度
本文关键字:字符串 何转换 转换 双精度 满足 如果 | 更新日期: 2023-09-27 18:20:01
考虑下面的类。
public class DoubleSegment
{
public int MinLength { get; }
public int MaxLength { get; }
public double Value { get; }
public string GetString(CultureInfo culture)
{
return Value.ToString(culture); // this is the easy but incorrect way
}
}
如您所见,长度要求被完全忽略,这显然是错误的。现在假设我们有 MinLength=4
、 MaxLength=4
和 Value=954
。如何将Value
转换为"0954"
?
请注意,此解决方案还必须与例如 MinLength=4
,MaxLength=10
和Value=58723.9843
,这将导致"58723.9843"
(至少对culture == CultureInfo.InvariantCulture
而言(。
您可以使用填充来填充字符串中的 0。
int value = 324;
var paddedValue = value.ToString().PadLeft(4,'0'));
String.PadLeft 方法。
string x= Value.ToString(culture);
x.PadLeft(MaxLength -x.Length,'0');
这比乍一看要复杂得多。您需要考虑:
- 字符串长度中包含小数点
- 如果没有小数的字符串表示形式超过最大长度,则输入无效,但是...
- 如果字符串表示形式仅超过小数的最大长度,则可以简单地对其进行舍入
我的解决方案:
public string GetString(CultureInfo culture) {
var integral = (int)Math.Truncate(Value);
var integralLength = integral.ToString().Length;
if (integralLength > MaxLength) {
throw new InvalidOperationException();
}
var integralWithDecimalSeparatorLength = integralLength + culture.NumberFormat.NumberDecimalSeparator.Length;
var minimumFixedPointLength = integralWithDecimalSeparatorLength + 1;
if (minimumFixedPointLength > MaxLength) {
var intValue = (int)Math.Round(Value);
return intValue.ToString("D" + MinLength, culture);
}
var precision = MaxLength - integralWithDecimalSeparatorLength;
return Value.ToString("F" + precision, culture);
}
首先,如果值的整数部分(不包括小数(太长,则值太大。否则,将根据剩余可用空间计算用于定点 ("F"( 字符串格式设置的精度。如果没有足够的空间,则使用舍入整数。定点格式的最小长度是整数、小数点和单个十进制数字(始终至少有一个,它不会仅格式化为尾随的小数点(。
对于MinLength=4
、MaxLength=4
和Value=954
,输出是"0954"
的,但是对于Value=54
,它是"54.0"
的,因为有足够的空间来.0
。这也将支持小数分隔符长度超过一个字符的区域性,尽管我不确定是否实际存在。
更多示例:
Value=987.654
, MinLength=4
, MaxLength=4
: "0988"
Value=987.654
, MinLength=3
, MaxLength=4
: "988"
Value=987.654
, MinLength=4
, MaxLength=5
: "987.7"
Value=987.654
, MinLength=4
, MaxLength=10
: "987.654000"
也许像这样偷摸摸?
int min_Length = 4;
int max_Length = 10;
dobule Value = 56665.66;
String temp = Value.ToString(culture); // this is the easy but incorrect way
if (temp.Length < min_Length)
{
while (temp.Length < min_Length)
{
temp = "0" + temp;
}
}
else if (temp.Length > max_Length)
{
temp = temp.Substring(0, max_Length);
}
return temp;