0

I need to format a number (decimal) into a string with minimal decimal points.
for example, let's say the minimal decimal point is 3

  • 123.123654 => 123.123654
  • 123.12 => 123.120
  • 123.1 => 123.100
  • 123 => 123.000

What is the best way to achieve this result?

J.Common
  • 1
  • 1
  • What is the *type* of the `number`? Is it `decimal` or `double`? If it's `decimal` just add `0.000m`: `string result = (number + 0.000m).ToString();` – Dmitry Bychenko Oct 17 '22 at 11:19
  • 1
    Floating point numbers cannot be stored exactly. So it is almost impossible to know how many decimal digits are significant. Related: [Is floating point math broken?](https://stackoverflow.com/q/588004/112968) – knittl Oct 17 '22 at 11:19
  • the number is a decimal – J.Common Oct 17 '22 at 11:22
  • For `decimal` you can do `num % 0.001M == 0` to determine if it has more or less than 3 significant digits and then format accordingly. – juharr Oct 17 '22 at 11:24

1 Answers1

2

If you use really a decimal the decimal places are preserved, so you can write:

decimal d = 123.120m;
Console.WriteLine(d);  // 123.120

If you can't do this you can always provide a format with ToString:

Console.WriteLine(d.ToString("N3")); 

Reading: Standard numeric format strings, especially. numeric format specifier

As juharr pointed out this shows just 3 decimal places. You can use string.Format:

string result = string.Format("{0:0.000##################}", d);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939