Convert number in a string to two decimal places

0

Let's imagine a string with the following value: 12,126456

How do I convert the string to 12.12?

I need to convert, using C #, so that the final string has a maximum of two digits after the comma.

I tried String.Format("{0:#,00}", valor ) but it did not work.

    
asked by anonymous 02.11.2017 / 15:46

3 answers

2

Since you do not need rounding, simply use the string manipulation:

var valor = "12,126456";
var commaPosition = valor.IndexOf(",", StringComparison.Ordinal);
var result = commaPosition+3 > valor.Length ? valor: valor.Substring(0, commaPosition + 3);

See in .NETFiddle

    
02.11.2017 / 16:00
2

Just convert to decimal, and then use the ToString by specifying the format.

using System;
using System.Globalization;

public class Program
{
    public static void Main()
    {
        string numero = "12,126456";
        decimal d;
        if (decimal.TryParse(numero,NumberStyles.Any, CultureInfo.CreateSpecificCulture("pt-BR"), out d))
        {
           Console.WriteLine("Arredondado: " + d.ToString("N2"));

           decimal t = Math.Truncate(d*100)/100;
           Console.WriteLine("Truncado: "+ t.ToString("0.##")); 

        }
        else
        {
            Console.WriteLine("Número inválido");
        }

    }
}
  

Result:

     

Rounded: 12.13

     

Truncated: 12.12

I put it in .NETFiddle: link

    
02.11.2017 / 15:55
0
Decimal meuValor = 0;
String minhaString = "010,87147";

meuValor = Math.Round(Convert.ToDecimal(minhaString), 2);

I have not dealt with errors, your string must always contain a comma to work correctly. If you are using "CultureInfo (" en-US "), replace the comma to be a dot. Ex:

minhaString.Replace(",", ".")

Do this before assigning the value to the variable Decimal.

    
02.11.2017 / 16:17