如何显示用户要求的位数?

时间:2018-12-27 06:06:26

标签: c#

例如:如果字符串值为“ 123456.7890”。 如果用户输入长度6,其他值2作为小数位。 输出值应类似于“ 123456.78”

如果用户输入长度5和其他值3作为小数位。 输出值应类似于“ 12345.789” 字符串s =“ 123456.7890”;

 string a = string.Format("{0, 2:F2}", s);
 int index = a.IndexOf('.');
 a = a.Substring(index, (a.Length-index));

3 个答案:

答案 0 :(得分:0)

最简单直接的方法是:

            var length = 5;
            var decimalPlaces = 2;
            var s = "123456.7890";
            var data = s.Split('.');
            var output1 = data[0].Substring(0, length);
            var output2 = data[1].Substring(0, decimalPlaces);
            var result = output1 + "." + output2;

答案 1 :(得分:0)

一种方法可能是这样的:

注意:如果字符串的长度小于您要输入的字符数,则代码将引发异常ArgumentOutOfRangeException

int LeftPlaces = 4;
int RightPlaces = 2;
String Input = "123456.7890";
String[] Splitted = Input.Split('.');
String StrLeft = Splitted[0].Substring(0, LeftPlaces);
String StrRight = Splitted[1].Substring(0, RightPlaces);
Console.WriteLine(StrLeft + "." + StrRight);

输出:1234.78

答案 2 :(得分:0)

如果您想在不使用字符串的情况下执行此操作,则可以这样做。

public decimal TrimmedValue(decimal value,int iLength,int dLength)
{
    var powers = Enumerable.Range(0,10).Select(x=> (decimal)(Math.Pow(10,x))).ToArray();
    int iPart = (int)value;
    decimal dPart = value - iPart;

    var dActualLength = BitConverter.GetBytes(decimal.GetBits(value)[3])[2];
    var iActualLength = (int)Math.Floor(Math.Log10(iPart) + 1);

    if(dLength > dActualLength || iLength > iActualLength)
        throw new ArgumentOutOfRangeException();
    dPart = Math.Truncate(dPart*powers[dLength]);
    iPart = (int)(iPart/powers[iActualLength - iLength]);
    return iPart + (dPart/powers[dLength]);
}

客户致电

Console.WriteLine($"Number:123456.7890,iLength=5,dLength=3,Value = {TrimmedValue(123456.7890m,5,3)}");
Console.WriteLine($"Number:123456.7890,iLength=6,dLength=2,Value = {TrimmedValue(123456.7890m,6,2)}");
Console.WriteLine($"Number:123456.7890,iLength=2,dLength=4,Value = {TrimmedValue(123456.7890m,2,4)}");
Console.WriteLine($"Number:123456.7890,iLength=7,dLength=3,Value = {TrimmedValue(123456.7890m,7,3)}");

输出

Number:123456.7890,iLength=5,dLength=3,Value = 12345.789
Number:123456.7890,iLength=6,dLength=2,Value = 123456.78
Number:123456.7890,iLength=2,dLength=4,Value = 12.789

最后一次调用会引发“ ArgumentOutOfRangeException”异常,因为该长度大于实际值