Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert 0.5 to 0.50 in C#

Tags:

c#

I have a string which holds 0.5. I have to convert in to 0.50.

I have tried following ways but nothing works.Please help

hdnSliderValue.Value is 0.5,I want workFlow.QualityThresholdScore to be 0.50

workFlow.QualityThresholdScore = Convert.ToDecimal(String.format("{0:d}",hdnSliderValue.Value));

workFlow.QualityThresholdScore = Convert.ToDecimal(String.format("{0:0.00}",hdnSliderValue.Value));

IS there any built in function or will i have to do string handling to accomplish this.

like image 297
Rohit Raghuvansi Avatar asked Jun 08 '10 07:06

Rohit Raghuvansi


2 Answers

The simplest way probably is to use string conversions:

string text = "0.5";
decimal parsed = decimal.Parse(text);
string reformatted = parsed.ToString("0.00");
decimal reparsed = decimal.Parse(reformatted);

Console.WriteLine(reparsed); // Prints 0.50

That's pretty ugly though :(

You certainly could do it by first parsing the original string, then messing around with the internal format of the decimal - but it would be significantly harder.

EDIT: Okay, in case it's an i18n issue, here's a console app which should definitely print out 0.50:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        CultureInfo invariant = CultureInfo.InvariantCulture;
        string text = "0.5";
        decimal parsed = decimal.Parse(text, invariant);
        string reformatted = parsed.ToString("0.00", invariant);
        decimal reparsed = decimal.Parse(reformatted, invariant);

        Console.WriteLine(reparsed.ToString(invariant)); // Prints 0.50
    }
}
like image 118
Jon Skeet Avatar answered Sep 22 '22 01:09

Jon Skeet


It's ToString("N2").

Edit: Add test code to show how it works

decimal a = 0.5m;
Console.WriteLine(a);
// prints out 0.5
string s = a.ToString("N2");
decimal b = Convert.ToDecimal(s);
// prints out 0.50
Console.WriteLine(b);
like image 41
Hans Olsson Avatar answered Sep 21 '22 01:09

Hans Olsson