Search code examples
c#visual-foxpro

STR( ) Function VFP C# equivalent


Is there an equivalent function in C# that works in same way as STR() in vfp https://msdn.microsoft.com/en-us/library/texae2db(v=vs.80).aspx

? str(111.666666,3,3) --> 112

? str(111.666666,2,3) --> ** error

? str(11.666666,2,3) --> 12

? str(0.666666,4,3) --> .667

? str(0.666666,8,3) --> 0.667 (ie 3 spaces from left plus the result)


Solution

  • As mentioned in comments you can use .ToString() to convert numbers to string. You can use standart formats or custom formats in ToString. For example ToString("C") gives you a string like $123.46 or €123.46 for value of "123.46" based on your locale settings.

    Or you can use custom formats like "0:#.##". You can use custom formats for different lengths or decimal places. For 2 decimal places "0:#.##" or for 3 decimal places "0:#.###".

    For detailed explanations you can check documentation.

    Standard numeric format strings: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

    Custom numeric format strings: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings

    Custom method for STR

    With the help of this link I wrote a quick sample. It works for your input but I did not test completely.

    public static string STR(double d, int totalLen, int decimalPlaces)
    {
        int floor = (int) Math.Floor(d);
        int length = floor.ToString().Length;
        if (length > totalLen)
            throw new NotImplementedException();
        if (totalLen - length < decimalPlaces)
            decimalPlaces =  totalLen - length;
        if (decimalPlaces < 0)
            decimalPlaces = 0;
        string str = Math.Round(d, decimalPlaces).ToString();
        if (str.StartsWith("0") && str.Length > 1 && totalLen - decimalPlaces - 1 <= 0)
            str = str.Remove(0,1);
    
        return str.Substring(0, str.Length >= totalLen ? totalLen : str.Length);
    }