Convert number to string to two decimal places

Asked

Viewed 5,991 times

0

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 at most two digits after the comma.

tried the String.Format("{0:#,00}", valor ) but it didn’t work.

3 answers

2

Just Convert to decimal, and then use 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");
        }

    }
}

Upshot:

Rounded: 12.13

Truncated: 12.12

I put in the . Netfiddle: https://dotnetfiddle.net/7ErUSv

  • 1

    Just to complement, if you want to give 12.12 you have to truncate the value before, since the formatting will use standard rounding.

  • I added the trunking part =] thanks @Maniero

  • does not work with negative this method

  • @ihavenokia Solved the issue of the negatives

2


Since it does not need to round, simply use the simple manipulation of the string:

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

See on .Netfiddle

  • this was the method I found more efficient, and simpler ;)

  • yes it is simple, but remember to test if the string contains "," before manipulating it, do a test with "12" for example. @ihavenokia

  • Yes, and also if the string has no less than 2 digits after the comma

  • @Rovannlinhalis The answer points to a possible approach, it was not intended to give a code ready for production. Meanwhile I changed to deal with the situation of fewer than two decimal places.

  • yes, it was just an observation for him to take in the implementation. =]

  • 1

    @Yes Rovannlinhalis, and I appreciate the comment as it allowed me to correct it.

Show 1 more comment

1

Decimal meuValor = 0;
String minhaString = "010,87147";

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

I have not treated errors, your string should 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 Decimal variable.

Browser other questions tagged

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