J.Common
J.Common

Reputation: 1

Format a number value with minimal decimal points

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

What is the best way to achieve this result?

Upvotes: 0

Views: 404

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460288

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);

Upvotes: 2

Related Questions