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.
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
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With