-2

We can use ToString("F4")) to get four decimal point in decimal datatype.

decimal test= 1234.123456789;
Console.WriteLine(test.ToString("F4"));

Is there a way just to specify precision of decimal point globally?

Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
Rohit Shrestha
  • 220
  • 1
  • 5
  • No, you use `ToString("F4"))`to get a four decimal point **`string`** representation of a `decimal`. That's different from specifying the "precision of a decimal". – Enigmativity Aug 13 '19 at 08:28
  • Also, the code in the question doesn't compile. – Enigmativity Aug 13 '19 at 08:29
  • Take a look at this: https://stackoverflow.com/questions/48212254/set-the-precision-for-decimal-numbers-in-c-sharp –  Aug 13 '19 at 08:29
  • 2
    And finally, would an extension method `string ToF4(this decimal value)` be sufficient for your needs? – Enigmativity Aug 13 '19 at 08:29
  • I suspect this is a [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You have a problem X (perhaps you want to represent money with a fixed number of decimal digits?) and assume Y is the solution - to somehow restrict the precision of `decimal` throughout the application. When you can't get Y to work you ask about Y, not the actual problem X. What is the *actual* question? Are you looking for the [Money Type](https://www.martinfowler.com/eaaCatalog/money.html) pattern perhaps? – Panagiotis Kanavos Aug 13 '19 at 08:37
  • As for formatting, `ToString()` is just one option and not even the most common. You can use `String.Format` to create a string with multiple arguments, eg `String.Format("{0:F4} at {1:s}",someNum,DateTime.Now)` or string interpolation with `$"{test:F3"}`. You can specify the format string in your UI controls too. – Panagiotis Kanavos Aug 13 '19 at 08:39
  • If the actual problem is how to *display* a specific property, you can also specify the display format with a data annotation attribute on a property, eg `[DisplayFormat(DataFormatString = "{0:F4}")]` and have the UI format the property value automatically – Panagiotis Kanavos Aug 13 '19 at 08:42

2 Answers2

1

You could create an extension method:

public static class DecimalExtensions
{
    public static string ToString4Points(this decimal d)
    {
        return d.ToString("F4");
    }
}

...and call it as:

decimal d = 1234.123456789m;
var str = d.ToString4Points();
kaffekopp
  • 2,551
  • 6
  • 13
1

You can use an extension.

On this way it works:

public class Program
{
    public static void Main()
    {
        decimal t = 1.0M;
        Console.WriteLine(t.ToStringD(2));
        Console.WriteLine(t.ToStringD());
    }
}

public static class Extensions
{
    private const int DEFAULT_PRECISION = 4;
    public static string ToStringD(this decimal value, int? precision = null)
        {
            return value.ToString("F" + (precision ?? DEFAULT_PRECISION).ToString());
        }
}
Kaitiff
  • 416
  • 3
  • 9