Barbara PM
Barbara PM

Reputation: 512

How do I round the number in a textbox to 2 decimals in C#?

I have a price textbox and I want to get a decimal value with 2 decimals, no matter the original string is a already a decimal or an integer. For example:

input = 12 --> output = 12.00
input = 12.1 --> output = 12.10
input = 12.123 --> output = 12.12

Upvotes: 3

Views: 5046

Answers (4)

hmqcnoesy
hmqcnoesy

Reputation: 4225

You can use the .ToString() overload that takes a string as a format:

var roundedInput = input.ToString("0.00");

Of course, this results in a string type.

To simply round, you can use Math.Round:

var roundedInput = Math.Round(input, 2);

You should be aware that by default, Math.Round uses "banker's rounding" method, which you might not want. In which case, you might need to use the overload that takes the rounding type enum:

var roundedInput = Math.Round(input, 2, MidpointRounding.AwayFromZero);

See the method overload documentation that uses MidpointRounding here: http://msdn.microsoft.com/en-us/library/ms131275.aspx

Also be aware that the default rounding method for Math.Round is different than the default rounding method used in decimal.ToString(). For instance:

(12.125m).ToString("N");  // "12.13"
(12.135m).ToString("N");  // "12.14"
Math.Round(12.125m, 2);   // 12.12
Math.Round(12.135m, 2);   // 12.14

Depending on what your situation is, using the wrong techniques could be very bad!!

Upvotes: 5

Mayank Pathak
Mayank Pathak

Reputation: 3681

Try

Input.Text = Math.Round(z, # Places).ToString();

Upvotes: 0

burning_LEGION
burning_LEGION

Reputation: 13450

use this method decimal.ToString("N");

Upvotes: 3

Pravin Pawar
Pravin Pawar

Reputation: 2569

// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

Upvotes: 3

Related Questions