Esraa_92
Esraa_92

Reputation: 1568

Convert string start with 0 to 2 decimal place asp.net?

I have this string:

Dim value as String = "0.11209176170341301"

And tried to use this code to convert the string into decimal with two places:

Dim value as String = "0.11209176170341301"
 Dim valueInDecimal As Decimal
            If [Decimal].TryParse(value, valueInDecimal) Then
                Console.WriteLine(valueInDecimal.ToString("0:0.#"))
            End If

I get this result:

11209176170341301D

I need to get this:

0.11

What I'm doing wrong?

I want to get as result a decimal with two placesfrom the string value

Upvotes: 0

Views: 226

Answers (2)

Akiner Alkan
Akiner Alkan

Reputation: 6872

You can use basic string operations also:

    string value = "0.11209176170341301";
    var parts = value.Split('.');
    var floatingPart = parts[1].Substring(0, 2);
    var truncatedValue = parts[0] + "," + floatingPart;

    decimal d = decimal.Parse(truncatedValue);
    string s = d.ToString();
    Console.Write(s);
    Console.Read();

If you are only needed it as string then you can just truncate it as string then it will be easier like:

    string value = "0.11209176170341301";
    var parts = value.Split('.');
    var floatingPart = parts[1].Substring(0, 2);
    var truncatedValue = parts[0] + "," + floatingPart;
    Console.Write(truncatedValue);

Or even you do not convert '.' to ',' then it will be like this:

    string value = "0.11209176170341301";
    var parts = value.Split('.');
    var floatingPart = parts[1].Substring(0, 2);
    var truncatedValue = string.Join(".",parts[0],floatingPart);
    Console.Write(truncatedValue);

Upvotes: 1

Amey Khadatkar
Amey Khadatkar

Reputation: 414

Use Math.Round function

        var x = "0.11209176170341301";

        Console.Write(Math.Round(Convert.ToDecimal(x), 2));

Upvotes: 0

Related Questions