# Format string question

Y

#### Yoavo

Hi,
I have a double value and I need to convert it to a string by leaving only 4
figits after the decimal point.
I do not want the value to be rounded.

For example if my input is:
double aa = 813.1234567

I want that my output string will be
"813.1234" (and not "813.1235").

I tried:
string MyStr = string.Format("{0:0.0000}, aa);

But this give me a rounded result.

Yoav.

Yoavo said:
Hi,
I have a double value and I need to convert it to a string by leaving only 4
figits after the decimal point.
I do not want the value to be rounded.

For example if my input is:
double aa = 813.1234567

I want that my output string will be
"813.1234" (and not "813.1235").

I tried:
string MyStr = string.Format("{0:0.0000}, aa);

Did you try, aa.ToString("#.####");

If that doesn't work, add another # and the use substring....

J.B. Moreno formulated on donderdag :
Did you try, aa.ToString("#.####");

If that doesn't work, add another # and the use substring....

That will still fail for a number 3.4999999999, the OP wants 3.4999 and
your method will make it 3.5000.

Try multiplying by 10000 (to get the decimals that are wanted to the
left of the decimal point), then convert it to int (cutting off
remaining decimals) and divide by 10000.0 again (a double value to get
a floating point division).
*Then* do a ToString() or ToString("#.####").

Hans Kesting

A smart work-around would be

double aa = 813.1234567;
string str = string.Format("{0:0.00000}", aa); //have 5 digits
after '.'
str = str.Remove(str1.Length - 1); //remove the fifth one

-Lav
http://lavbox.blogspot.com

Yoavo said:
Hi,
I have a double value and I need to convert it to a string by leaving
only 4 figits after the decimal point.
I do not want the value to be rounded.

For example if my input is:
double aa = 813.1234567

I want that my output string will be
"813.1234" (and not "813.1235").

I tried:
string MyStr = string.Format("{0:0.0000}, aa);

But this give me a rounded result.

Yoav.

The value will always be rounded at some point to prevent problems with
the limited precision of floating point numbers.

The closest you can get is if you format the number with a full set of
decimals, then use string manipulation to remove decimals:

string s = aa.ToString();
int pos = s.IndexOf(.);
if (pos != -1 && pos + 5 < s.Length) {
s = s.Substring(0, pos + 5);
}

Lav said:
A smart work-around would be

double aa = 813.1234567;
string str = string.Format("{0:0.00000}", aa); //have 5 digits
after '.'
str = str.Remove(str1.Length - 1); //remove the fifth one

-Lav
http://lavbox.blogspot.com

It's not so smart when it doesn't work...

double aa = 813.123499;

gives str = "813.1250"