Reputation: 29729
How can I customize a function in which I print doubles? I would like this function to get number of digits after the decimal point (comma in my locale) as an agrument and then print, for example, pi with the number of digits after comma specified by user.
Upvotes: 1
Views: 3212
Reputation: 1653
String.Format might help you out using the NumberFormatInfo.NumberDecimalDigits property.
Code example from 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
Upvotes: 2
Reputation: 3130
I am telling you in a way, that i solved a similar problem in my project.
Convert the resulting value to a string. Since you use like pi = 3,14
String Result = "3,14";
using
Split(Char()) //use a comma to split this into array
You will get a array now, array[1] will give you the second part.
Since its still a string, use string.Length()
function to get the Length, (nothing but the number of digits that comes after the comma).
You can now print the resulting digits in whichever way you want
Upvotes: -1
Reputation: 8531
var digits = 4;
var myDouble = Math.PI;
var formattedValue = myDouble.ToString("N" + digits.ToString(),
CultureInfo.CurrentCulture);
Upvotes: 5