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.

Please advise,
Yoav.
 
J

J.B. Moreno

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....
 
H

Hans Kesting

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
 
G

Göran Andersson

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.

Please advise,
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);
}
 
G

Göran Andersson

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"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top