我的 float 是 100.0,当我将其转换为字符串时,它变成了 100。
rmt.MinNumber = 0.0;
rmt.MaxNumber = 100.0;
rmt.MaxLength = rmt.MinNumber.ToString() + " - " + rmt.MaxNumber.ToString();
我知道我能做到
rmt.MinNumber.ToString("0.0");
但这也是保存在 rmt.Decimal 中的设置,所以
如果 rmt.Decimal = 1 然后rmt.MaxLength = 100.0
如果 rmt.Decimal = 2 然后 rmt.MaxLength = 100.00 等等...
如何将其转换为保留其十进制值的字符串
更新
按照 CodeFuller 的建议
public static class Helper
{
public static string Format(this float f, int n)
{
return f.ToString($"0.{new String('0', n)}");
}
}
但目前它给了我预期的错误
最佳答案
您仍然可以使用 ToString("0.0")
方法,但您应该在运行时构建格式说明符,因为点后的位数会有所不同。
考虑使用以下扩展方法:
public static class FloatExtensions
{
public static string Format(this float f, int n)
{
// return f.ToString($"0.{new String('0', n)}");
return f.ToString("0." + new String('0', n));
}
}
rmt.MaxLength = rmt.MinNumber.Format(rmt.Decimal)
关于c# - 将 float 转换为保留小数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47447727/