473,499 Members | 1,562 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Variable precision in numeric format string

I'm trying to output a double using a precision that
varies, governed by the value of a precision variable.
In C I can do it like this:

double pi = 3.14159;
int prec = 4;

printf( "%.*f", prec, pi ); // 3.1416

The * in "%.*f" says to use the value of the next
argument (must be an int) for the precision. Is there
a numeric format in C# that can do this? The best
workaround I've come up with is:

double pi = 3.14159;
int prec = 4;

StringBuilder sb = new StringBuilder( "#0." );
sb.Append( new string( '0', prec ) ); // sb = "#0.0000"

Console.Write( pi.ToString( sb.ToString() ) ); // 3.1416

Thanks,
Mason Deaver
General Dynamics C4 Systems, VertexRSI

Dec 6 '05 #1
2 4217
Here are 3 example methods:

// using ToString, IndexOf, and Substring
public static string FormatDoubleA(double d, int precision)
{
string precise = pi.ToString();
return precise.Substring(0, piPrecise.IndexOf('.') + prec);
}

// Using NumberFormatInfo
public static string FormatDoubleB(double d, int precision)
{
System.Globalization.NumberFormatInfo nfi =
new System.Globalization.CultureInfo( "en-US",
false ).NumberFormat;
nfi.NumberDecimalDigits = precision;
return d.ToString("F", nfi);
}

// Using Standard Numeric format string
public static string FormatDoubleC(double d, int precision)
{
return d.ToString("F" + precision.ToString());
}

I'm not sure which of these three is the most efficient, but I suspect it is
the third. I would suspect that the second is the least efficient.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
You can lead a fish to a bicycle,
but you can't make it stink.

<md*********@yahoo.com> wrote in message
news:11*********************@z14g2000cwz.googlegro ups.com...
I'm trying to output a double using a precision that
varies, governed by the value of a precision variable.
In C I can do it like this:

double pi = 3.14159;
int prec = 4;

printf( "%.*f", prec, pi ); // 3.1416

The * in "%.*f" says to use the value of the next
argument (must be an int) for the precision. Is there
a numeric format in C# that can do this? The best
workaround I've come up with is:

double pi = 3.14159;
int prec = 4;

StringBuilder sb = new StringBuilder( "#0." );
sb.Append( new string( '0', prec ) ); // sb = "#0.0000"

Console.Write( pi.ToString( sb.ToString() ) ); // 3.1416

Thanks,
Mason Deaver
General Dynamics C4 Systems, VertexRSI

Dec 6 '05 #2
Thanks, Kevin. Your third method will work fine for me.

By the way, method 1's return statement needs to be written
like this to avoid an off-by-one-digit error:

return precise.Substring(0, precise.IndexOf('.') + prec + 1);

This method won't round up when needed, e.g., using my
original precision value you'll get 3.1415 instead of 3.1416.
Methods 2 and 3 do round correctly.

Mason Deaver
General Dynamics C4 Systems, VertexRSI

Dec 6 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
3634
by: Joshua Forgione | last post by:
Hello. I am reverse engineering some Python Code. I am using the book "The Quick Python Book" as an aide. The following line exists in the code: msg = struct.pack('BBBB',word0, word1, word2,...
1
4627
by: Jose Gonzalez | last post by:
How to apply a numeric format to a textbox using xhtml? I know you have to use the "-wap-input-format" style tag in css. I can get this to work in a regular xhtml page, however, I've been...
1
1484
by: kevininstructor | last post by:
The following was copied from a web site for learning formatting. Dim myInt As Integer = 100 Dim FormatPrice As String = String.Format("Price = |{0,10:c }|", myInt) Console.WriteLine(FormatPrice)...
3
14814
by: Mark | last post by:
I have a Decimal or a Double - your choice. I'd like to print the number as string with a specified number of decimal places. Let's say my number 110.5, and I'd like to capture it in a string...
2
1565
by: MM | last post by:
Hi, I have a param class containg these vars:- string key; // eg: "WN" object value; // eg: 1.2 string format; // eg "F2" and I output these to a StreamWriter using ...
6
1663
by: Larry Lard | last post by:
I am trying to apply the following easy-to-state formatting rule to display a number: - If the number is positive or negative, display it in the 'default' way - If the number is zero, the...
7
5459
by: Tony Girgenti | last post by:
Hello. Trying to develop VS2005, SP1 windows form VB program. When i try a statement like below and the data is "24.95", without the quotes of course, regPriceString equals "000000000025+" . ...
2
1435
by: zionlion | last post by:
PHP code How can I retrieve elements of an array in numeric format? Look at this code: $query = "SELECT price FROM $tbl_name"; $result = mysql_query($query) or die(mysql_error()); ...
7
13610
by: Andrus | last post by:
How to create format string for decimal data type which shows blank for zero and default format otherwize ? I tried format string "f;f;#" but this shows f for nonzero numbers. Andrus. ...
0
7130
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7220
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6893
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
5468
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4918
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4599
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
3098
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3090
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1427
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.