在小数点后用数字打印双精度数

如何自定义打印双打的function? 我希望这个函数得到小数点后面的位数(我的语言环境中的逗号)作为一个agrument,然后打印,例如pi,用户指定逗号之后的位数。

var digits = 4; var myDouble = Math.PI; var formattedValue = myDouble.ToString("N" + digits.ToString(), CultureInfo.CurrentCulture); 

String.Format可能会帮助您使用NumberFormatInfo.NumberDecimalDigits属性。

MS的代码示例。

 Public Shared Sub Main() //' Gets a NumberFormatInfo associated with the en-US culture. Dim nfi As NumberFormatInfo = New CultureInfo("en-US", False).NumberFormat //' Displays a negative value with the default number of decimal digits (2). Dim myInt As Int64 = - 1234 Console.WriteLine(myInt.ToString("N", nfi)) //' Displays the same value with four decimal digits. nfi.NumberDecimalDigits = 4 Console.WriteLine(myInt.ToString("N", nfi)) End Sub 

我在某种程度上告诉你,我在项目中解决了类似的问题。

将结果值转换为字符串。 因为你使用像pi = 3,14

 String Result = "3,14"; 

运用

Split(Char())//使用逗号将其拆分为数组

你现在会得到一个数组,array [1]会给你第二部分。

因为它仍然是一个字符串,所以使用string.Length()函数来获取Length,(除了逗号后面的位数)。

您现在可以以您想要的任何方式打印结果数字