Reputation: 2864
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.
Upvotes: 6
Views: 4603
Reputation:
Stringy version since no-one has suggested it.
string pointFive = "0.5";
int decimals = (pointFive.Length-1) - pointFive.IndexOf('.');
if (decimals >= pointFive.Length)
pointFive += ".00";
else if (decimals == 1)
pointFive += "0";
else if (decimals == 0)
pointFive += "00";
Might even be quicker than numeric conversions and formatting functions.
Upvotes: 0
Reputation: 55039
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);
Upvotes: 2
Reputation: 1502166
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
}
}
Upvotes: 9
Reputation: 358
Have you tried workFlow.QualityThresholdScore = Convert.ToDecimal(hdnSliderValue.Value.ToString("N2"));
Upvotes: 0
Reputation: 61467
In numerics, 0.5 == 0.50. A zero doesn't add any information, so if QualityThresholdScore is of a numeric type, you will get 0.5 no matter what. If it is a string, use decimal.ToString("0.00");
.
Upvotes: 0