473,545 Members | 1,471 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 4227
Here are 3 example methods:

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

// Using NumberFormatInf o
public static string FormatDoubleB(d ouble d, int precision)
{
System.Globaliz ation.NumberFor matInfo nfi =
new System.Globaliz ation.CultureIn fo( "en-US",
false ).NumberFormat;
nfi.NumberDecim alDigits = precision;
return d.ToString("F", nfi);
}

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

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*********@ya hoo.com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.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.Substri ng(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
3642
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, word3, word4) In this struct.pack command, the format string is 'BBBB.' In the book, it gives the following examples for characters that are...
1
4634
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 unsuccessful in getting it to work in asp.net 1.1 The following code has allowCustomAttributes set and works fine for labels, but not for textboxes. This...
1
1494
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) The result shown is no number but the character c as in the format string. Is the format not valid in this context? Thanks for your assistance,...
3
14818
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 with 3 decimal places: "110.500". How do you do this? My method below isn't working so hot. Decimal dcTotal = 110.5; string strMyString =...
2
1570
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 nc_file.Write("{0}{1:" + param.format + "}", param.key, param.value);
6
1668
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 output should be an empty string Now I know this is trivial to code, but the elegant solution would be passing a custom format string to ToString()....
7
5467
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+" . regPriceString = String.Format("{0:000000000000+}", merchandiseDataRow.Item("RegPrice"))
2
1439
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()); while($row = mysql_fetch_row($result)) {
7
13624
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. using System.Windows.Forms;
0
7465
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7656
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7805
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7752
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5325
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4944
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3449
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 last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1878
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 we have to send another system

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.