2017-09-15 116 views
0

有没有在C#中的等价功能,在相同的方式, STR()在VFP https://msdn.microsoft.com/en-us/library/texae2db(v=vs.80).aspxSTR()函数VFP C#相当于

的作品? 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(即从左边3个空格加上结果)

+1

你可以用它来形容句子吗?如果你只有'STR(n)',看起来像'n.ToString()'。 – Ryan

+0

是的,文档说它返回*数字表达式的字符相当*所以'ToString'将完成这项工作,但它也允许指定小数位数,因此可能是一个好主意来检出https:// docs。 microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings – DavidG

+0

['STR(nExpression [,nLength [,nDecimalPlaces]])](https://msdn.microsoft.com /en-us/library/texae2db(v=vs.80).aspx)是'nExpression.ToString()'加['nLength'](https://stackoverflow.com/q/3566830/1997232)和[' nDecimalPlaces'](https://stackoverflow.com/q/6951335/1997232)(as [format](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-格式化字符串))。 – Sinatr

回答

2

正如评论中提到的,您可以使用.ToString()将数字转换为字符串。您可以在ToString中使用标准格式或自定义格式。例如ToString(“C”)根据您的语言环境设置为您提供123.46或123.46英镑的字符串作为“123.46”的值。

或者您可以使用自定义格式,如“0:#。##”。您可以使用不同长度或小数位的自定义格式。 2位小数位“0:#。##”或3位小数位“0:#。###”。

有关详细说明,您可以检查文档。

标准数字格式字符串:https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

自定义数字格式字符串:对于STR

有了这个link的帮助下,我写了一个快速样品https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings

自定义方法。它适用于您的输入,但我没有完全测试。

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); 
} 
+0

我不认为这是很简单的字符串。 – mehwish

+0

它根据传递的值做了各种事情,例如,如果最大长度小于小数位数,它将围绕数字,如果最大长度大于其填充空格的结果 – mehwish

+0

您可以提供一些值作为示例ToString不够? – fofik