How to limit decimal places using C#

Asked

Viewed 12,946 times

3

I’m having some difficulty limiting the decimal places in C# .

double x = 1,41293

I wanted to output only from 1.412 I have tested the following code:

Convert.ToDecimal(x).ToString("0.00", CultureInfo.InvariantCulture)

and

Convert.ToDecimal(x).ToString("N3", CultureInfo.InvariantCulture)
  • change the comma by a point: double x = 1.41293

  • @Rovannlinhalis I can’t do that, that’s why I use Cultureinfo.Invariantculture

  • 2

    This is from C#, which like other programming languages use . as decimal separator, including this first line, will give compilation error, unless it is a string

  • But I can’t change that point

2 answers

3


If it is a string, with comma as decimal separator, put the CultureInfo in the Convert:

decimal x = Convert.ToDecimal("1,41293", new CultureInfo("pt-BR"));

Console.WriteLine(x.ToString("N3"));    //Resultado: 1.413

If necessary, output also with decimal separator to comma, put the CultureInfo in the ToString():

Console.WriteLine(x.ToString("N3", new CultureInfo("pt-BR") ));   //Resultado: 1,413
  • But then I will get the output of 1.41293 , I need to get only the first 3 numbers ie 1.412

  • the output is being 1.413 or 1.413

0

Good Night advise receiving the direct amount and treat on exit.

double x = 1.41293

 Console.Writeln("X={0;f3}",x);
 // f3 --> formatação de saída para float com 3 casas

I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.