Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Format % with significant figures

I am using the following code to show percentage using String.Format but I also want to limit the number of significant figures to 2, the two don't seem to play well together. How can I get the two working together properly?

String.Format("% Length <= 0.5: {0:0%}", m_SelectedReport.m_QLT_1);

So what I ideally want is something like this

double d1 = 1234;
double d2 = 0.1234;

//Output of d1 -> 12
//Output of d2 -> 0.12
like image 414
Chris Avatar asked Jun 21 '10 14:06

Chris


People also ask

What is %s in string format?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.

How do you format a significant figure in Python?

The “g” format specifier is a general format that can be used to indicate a precision, or to indicate significant digits. To print a number with a specific number of significant digits we do this: print '{0:1.3g}'. format(1./3.)

What is %g in Python?

'g' or 'G' Floating point format. Uses exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.

How do you round to significant figures?

It rounds to the most important figure in the number. To round to a significant figure: look at the first non-zero digit if rounding to one significant figure. look at the digit after the first non-zero digit if rounding to two significant figures.


2 Answers

You can control the number of digits before and after the decimal point (separator). Controlling the total number of digits (before and after) is going to require some programming.

The format {0:0.00%} ought to work, giving outputs like 0.12, 1.23 and 12.34

like image 106
Henk Holterman Avatar answered Sep 29 '22 20:09

Henk Holterman


String test = String.Format("{0:F2}", 25);

This will create 25.00

All the numeric formatting options can be found on MSDN. I use it all the time.

http://msdn.microsoft.com/en-us/library/s8s7t687.aspx

like image 27
Justin Avatar answered Sep 29 '22 20:09

Justin