Learner
Learner

Reputation: 1376

How to remove all digits after . value except two digits c#

I am getting string value like 123.00000000.
Now I want to take only 123.00 value. So how can I remove all last digits except two digits after value.
For example:

textBox1.Text="123.00000000"; I want like textBox1.Text="123.00"; Thanks in advance!

Upvotes: 0

Views: 2293

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460288

Use the proper string format.

double value = double.Parse("123.00000000", CultureInfo.InvariantCulture);
textBox1.Text = value.ToString("N2");

Standard Numeric Format Strings

Demo

Edit: The string.Substring has the problem that only half of the world uses the . as decimal separator. So you need to know the culture in which the input was converted from a number to a string. If it's the same server you can use CultureInfo.CurrentCulture (or omit it since that is the default):

double originalValue = 123;
// convert the number to a string with 8 decimal places
string input = originalValue.ToString("N8");
// convert it back to a number using the current culture(and it's decimal separator)
double value = double.Parse(input, CultureInfo.CurrentCulture);
// now convert the number to a string with two decimal places
textBox1.Text = value.ToString("N2");

Upvotes: 3

Mudassir Hasan
Mudassir Hasan

Reputation: 28771

string str = "123.00000000";
textBox1.Text = str.Substring(0,str.IndexOf(".")+3);

Upvotes: 2

Tobia Zambon
Tobia Zambon

Reputation: 7629

see here for a complete overview of how to format numbers. In your case it is:

textBox1.Text = String.Format("{0:0.00}", 123.0);

Upvotes: 1

Related Questions