How can I remove zeros and decimal points from decimal strings?

The following code is currently being displayed:

12.1 12.100 12.1000 12.00 12 12.0000 

How can I change it so that it displays:

 12.1 12.1 12.1 12 12 12 

Math.Round seems to be a thing, but it forces me to determine how many decimal places I want, but I want them to be variables as above.

If there is no mathematical way to do this, I will simply delete the zeros and decimal points on the right side of the lines, but I think there is a mathematical way to handle this.

 using System; using System.Collections.Generic; namespace Test8834234 { public class Program { static void Main(string[] args) { List<string> decimalsAsStrings = new List<string> { "12.1", "12.100", "12.1000", "12.00", "12", "12.0000" }; foreach (var decimalAsString in decimalsAsStrings) { decimal dec = decimal.Parse(decimalAsString); Console.WriteLine(dec); } Console.ReadLine(); } } } 
+4
decimal c # rounding
Jan 23 '10 at 12:40
source share
4 answers

You can also use decimal ToString with the parameter:

 string s = dec.ToString("0.#"); 

Note. You may have an internationalization problem with your code. As you encoded it, it will use the culture information from the user computer, which may have something other than . for decimal separator. This can lead to the fact that your program will give incorrect results for users with . for thousands separator.

If you want to ensure that the parse method always behaves the same, you can use CultureInfo.InvariantCulture . If you really want to parse the string according to the custom culture settings, then what you are doing is fine.

+10
Jan 23
source share

Using:

  Console.WriteLine("{0:0.####}", dec); 

Read more about numeric format strings here.

+4
Jan 23 '10 at 12:45
source share

This line format should make your day: "0. ###############################". Keep in mind that decimals can have no more than 29 significant digits.

Examples:

 ? (1000000.00000000000050000000000m).ToString("0.#############################") -> 1000000.0000000000005 ? (1000000.00000000000050000000001m).ToString("0.#############################") -> 1000000.0000000000005 ? (1000000.0000000000005000000001m).ToString("0.#############################") -> 1000000.0000000000005000000001 ? (9223372036854775807.0000000001m).ToString("0.#############################") -> 9223372036854775807 ? (9223372036854775807.000000001m).ToString("0.#############################") -> 9223372036854775807.000000001 
+1
Sep 10 2018-11-11T00:
source share
 public static string RemoveDecimalsFromString(string input) { decimal IndexOfDot = input.IndexOf("."); StringBuilder sb = new StringBuilder(); for (int i = 0; i < IndexOfDot; i++) { sb.Append(input[i]); } return sb.ToString(); } 
0
Jun 20 '17 at 16:52
source share



All Articles