简体   繁体   中英

Rounding to 2 decimal places c#

Currently have a working rounding model within my c# code and is perfectly rounding numbers that have more than 2 decimal places down to 2 decimal places which is great. However, when i have lets say double value = 100.6 , and i put that into double dollar_value = Math.Round(value, 2) , it still returns as 100.6.

I was wondering if there was a way to transform a 1 decimal place value to 2 decimal places?

Numbers are not stored with extra zeroes (As it is a waste of memory to do so, being the numbers are the same with or without). In order to represent a number this way you will either need to display or store it as a string.

string str = value.ToString("#.00", CultureInfo.InvariantCulture);

Now str will always have 2 decimal places.

I don't know the C# method, but in C++ I'd use one of these two methods:

double value = 23.666666 ; // example
value = 0.01 * floor ( value * 100.0 ) ; // There's a "floor" function in C# too

^ See https://msdn.microsoft.com/en-us/library/e0b5f0xb(v=vs.110).aspx

Or

double value = 23.666666 ; // example
value = 0.01 * (double) ( (int)(value*100.0) ) ;

Or

double value = 23.666666 ; // example
value = 0.01 * double ( int ( value*100.0 ) ) ; // same as previous, but more C++ like

The other answers are probably better if you're looking to "print a dollar amount with two decimal places." However, if you want to transform the number to use internally, this is a way to do it.

If you want the string representation to have two decimal points use: yourNumber.ToString ("0.00");

The number itself is always stored as a ~29 digit number regardless of its string representation.

Your value just needs to be formatted when it's display - for example value.ToString("N2") will convert it to a string with two decimal places. Check out the Standard Numeric Format Strings on MSDN to see a broader list of formatting strings.

Additionally, I'd only convert to a string when you're ready display the value to a user and would keep it as a numeric type (eg double) if you're passing it around between methods or planning to do any further calculations on it. Otherwise you'll be unnecessarily converting the value to and from a string multiple times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM