I am use the textbox value like 1455.23, use the round function my output is 0000145523 but customer not enter float values like 1234 my output is 0000123400 pls give me suggestion
my code is format.cs
public bool formatAmount(float flAmount, out string strOutput)
{
bool bval = false;
float rounded = (float)Math.Round(flAmount, 2);
if(rounded!=null)
{
flAmount = flAmount * 100;
strOutput = Convert.ToString(flAmount);
bVal = true;
}
return bVal;
}
In my asp page code like this
string ods;
float a = Convert.Todecimal(txtSSA.Text);
string sss = oclsUtility.formatAmount(a, out ods);
I am assuming you want to ignore the multiplication of 100 part in case the fractional value is not there.
So 1234 in your case is essentially 1234.00 and you need to avoid the 0000123400
float flAmount = 15F;
float rounded = (float)Math.Round(flAmount, 2);
double fractionalval = (rounded - Math.Floor(rounded)) * 100;
if(fractionalval > 0)
flAmount = flAmount * 100;
After this i presume rest might work and pad it to 10 length string.
This would skip the multiplication if there are fractional parts, hope this is what you need else please edit for additional information.
If I'm understanding you, you need to keep leading 0 if user input is float and if not removes them. You can try this:
int number;
bool result = Int32.TryParse(rounded, out number);
if (result)
{
// Your number will contain the number with no leading 0
}
else
{
// Then you have a float.
}
Related
Let's say I have the following code:
int digit1 = 1;
int digit2 = 3;
and I need to combine the two integers, resulting in a floating-point number equal, in this case, to 13.0f. This is probably easy, as I'm new to C# and learning it from a book, but how is it done?
Example:
int digit1 = 3;
int digit2 = 6;
float result = combine_integers (digit1, digit2);
// result = 36
NOTE:
I don't actually need a function. I just did that for the sake of the example.
float combine_integers (int digit1, int digit2)
{
return 10*digit1 + digit2;
}
Example
combine_integers(1, 3) ==>
10 * 1 + 3 ==>
10 + 3 ==>
13
combine_integers(3, 6) ==>
10 * 3 + 6 ==>
30 + 6 ==>
36
If your integers are single digits, then abelenky's answer above is going to do it quickest for you. If they're not single digits, then you could do string.Format() as above, but there's also a couple of edge cases that aren't covered, such as negative values or both values being 0.
The string operations above could produce results such as "00", "5-1", or throw an error for not being able to parse the string result. In the case of {5,-1}, you could end up with 49.
What I would do is cover my bases and assume that if you use a negative number, you want the absolute value. This code also covers the base case of single digits, but gives you some flexibility so that combine_integers(12,34) returns 1234.0f.
static float combine_integers (int digit1, int digit2)
{
int checker = Math.Abs(digit2);
int result = Math.Abs(digit1);
do
{
result *= 10;
checker /= 10;
} while(checker>0);
result += Math.Abs(digit2);
return (float)result;
}
private static float combine_integers(int a, int b)
{
return float.Parse(a.ToString() + b.ToString());
}
https://dotnetfiddle.net/M9Bpwt
Try this code:
int digit1 = 3;
int digit2 = 6;
string concat = string.Format("{0}{1}", digit1, digit2);
float result = float.Parse(concat);
I am attempting to manually convert numbers between decimal and hexadecimal. I have it working for positive numbers and converting a negative decimal to 'negative' hexadecimal but I can't convert it from 'negative' hexadecimal to negative decimal.
Here is the code I am attempting to work with:
private string HexToDecimal(char[] toConvert)
{
if (negativeValue)
{
negativeValue = false;
long var = Convert.ToInt64(HexToDecimal(ResultLabel.Text.ToCharArray()));
long valueToHex = var - (long)Math.Pow(16, 15);
return ResultLabel.Text = valueToHex.ToString();
}
else
{
double total = 0;
//Convert hex to decimal
HexOrDecimalLabel.Text = "Decimal";
//TODO: create int array from indivial int
char[] charArray = toConvert;
long[] numberArray = HexSwitchFunction(charArray);
//TODO: reverse array
Array.Reverse(numberArray);
//loop array, times value by 16^i++, adding to total. This is the method used to convert hex to decimal
double power = 0;
foreach (int i in numberArray)
{
total += (i * (Math.Pow(16, power)));
power++;
}
//set the result label to total
isHex = false;
AllowHexButtons();
return ResultLabel.Text = total.ToString();
}
}
For instance, I can turn - 10 into FFFFFFFFFFFFFFF6, but when i attempt to turn that into decimal, I get 1.15292150460685E+18, which I can't do any equations with.
Does anyone know of a way around this?
This is because double uses a different representation for negative numbers. Changing the type of total and power from double to long will fix the problem.
The Task:
Create a hourly pay calculator which is simple to use but effective.
private double amount4Hours = 4;
private double amount8Hours = 8;
private double amount10Hours = 10;
private void btnSubtotal_Click(object sender, EventArgs e)
{
double answer;
// 45 min break removal
double break45 = 0.75;
double outputValue = 0;
bool isNumber = true;
//true false statement for error checking
isNumber = double.TryParse(text4Hours.Text, out outputValue);
isNumber = double.TryParse(text8Hours.Text, out outputValue);
isNumber = double.TryParse(text10Hours.Text, out outputValue);
if (!isNumber)
{
//error checking for blank text boxes
MessageBox.Show("Enter a number from 0-9");
}
else
{
//calculates total amount of hours after breaks have been removed
amount4Hours = amount4Hours * double.Parse(text4Hours.Text);
amount8Hours = amount8Hours * double.Parse(text8Hours.Text) -
break45 * double.Parse(text8Hours.Text);
amount10Hours = amount10Hours * double.Parse(text10Hours.Text) -
break45 * double.Parse(text10Hours.Text);
// Adds all together to output final amount of hours
answer = amount4Hours + amount8Hours + amount10Hours;
labSubtotal.Text = answer.ToString();
}
}
private void btnPay_Click(object sender, EventArgs e)
{
// Hourly pay stored here
double hourpay = 6.19;
hourpay = hourpay * double.Parse(labSubtotal.Text);
labPay.Text = hourpay.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
// Resets all text boxes back to blank
text4Hours.Text = string.Empty;
text8Hours.Text = string.Empty;
text10Hours.Text = string.Empty;
labSubtotal.Text = string.Empty;
labPay.Text = string.Empty;
}
}
}
The Problem...
When I type in three different numbers in each text box, I get the outcome just perfect.
If I hit the clear button, it does what I ask and removes everything from the output
If I enter three numbers again (same ones or different ones) after it has been cleared, I will get different output.
I think it has something to do with the clear code because it's not resetting the values to zero like it does at the start of the program. I have tried setting the clear code to input zeros, but that doesn't help; just gives the same problem.
This is a good case to show how to use the debugger. Put a breakpoint on the line:
amount4Hours = amount4Hours * double.Parse(text4Hours.Text);
Then when you calculate the answer, watch how the amount4Hours variable changes.
This type of bug shows why people avoid the use of global variables.
private double amount4Hours = 4;
private double amount8Hours = 8;
private double amount10Hours = 10;
This code should go into your btnSubtotal_Click.
amount4Hours = 4;
amount8Hours = 8;
amount10Hours = 10;
Put this code in clear button. You also need to reset your global variables.
As others have said, on a general point you need to use the debugger for figuring out why something hasn't worked as you expected. In this case you are creating 3 global variables at the beginning (amount4hours etc.) and then manipulating them later on when clicking btnSubmit. At no point when btnClear do you reset your global values. Try adding in your btnClear_Click method:
amount4hours = 4;
amount8hours = 8;
amount10hours = 10;
This will reset your global variables.
If the global variables value should not be updated,why not directly get the value of answer by having their sum value directly
/*amount4Hours = amount4Hours * double.Parse(text4Hours.Text);
*
* amount8Hours = amount8Hours * double.Parse(text8Hours.Text) -
* break45 * double.Parse(text8Hours.Text);
*
* amount10Hours = amount10Hours * double.Parse(text10Hours.Text) -
* break45 * double.Parse(text10Hours.Text);
*
* answer = amount4Hours + amount8Hours + amount10Hours;*/
answer = amount4Hours * double.Parse(text4Hours.Text) +
amount8Hours * double.Parse(text8Hours.Text) -
break45 * double.Parse(text8Hours.Text) +
amount10Hours * double.Parse(text10Hours.Text) -
break45 * double.Parse(text10Hours.Text);
By the way, your error checking is fail because you stored all checking result in same variable therefore only the third textbox content is checked based on your logic. I assume you display the MessageBox whenever one of three textbox have invalid input. Then,
//bool isNumber = true;
//true false statement for error checking
//isNumber = double.TryParse(text4Hours.Text, out outputValue);
//isNumber = double.TryParse(text4Hours.Text, out outputValue);;
//isNumber = double.TryParse(text10Hours.Text, out outputValue);
//if (!isNumber)
if (!double.TryParse(text4Hours.Text, out outputValue)||
!double.TryParse(text8Hours.Text, out outputValue)||
!double.TryParse(text10Hours.Text, out outputValue))
{
//error checking for blank text boxes
//the checking only check if they are double type
//but not checking the range from 0 to 9
MessageBox.Show("Enter a number from 0-9");
}
I need to format a double value so that it fits within a field of 13 characters. Is there a way to do this with String.Format or am I stuck with character-by-character work?
Edits: (hopefully they will stay this time)
With cases greater than a trillion I am to report an error. It's basically a calculator interface.
My own answer:
private void DisplayValue(double a_value)
{
String displayText = String.Format("{0:0." + "".PadRight(_maxLength, '#') + "}", a_value);
if (displayText.Length > _maxLength)
{
var decimalIndex = displayText.IndexOf('.');
if (decimalIndex >= _maxLength || decimalIndex < 0)
{
Error();
return;
}
var match = Regex.Match(displayText, #"^-?(?<digits>\d*)\.\d*$");
if (!match.Success)
{
Error();
return;
}
var extra = 1;
if (a_value < 0)
extra = 2;
var digitsLength = match.Groups["digits"].Value.Length;
var places = (_maxLength - extra) - digitsLength;
a_value = Math.Round(a_value, places);
displayText = String.Format("{0:0." + "".PadRight(_maxLength, '#') + "}", a_value);
if (displayText.Length > _maxLength)
{
Error();
return;
}
}
DisplayText = displayText;
}
If this is calculator, then you can not use character-by-character method you mention in your question. You must round number to needed decimal places first and only then display it otherwise you could get wrong result. For example, number 1.99999 trimmed to length of 4 would be 1.99, but result 2 would be more correct.
Following code will do what you need:
int maxLength = 3;
double number = 1.96;
string output = null;
int decimalPlaces = maxLength - 2; //because every decimal contains at least "0."
bool isError = true;
while (isError && decimalPlaces >= 0)
{
output = Math.Round(number, decimalPlaces).ToString();
isError = output.Length > maxLength;
decimalPlaces--;
}
if (isError)
{
//handle error
}
else
{
//we got result
Debug.Write(output);
}
You have a lot formatting options using String.Format, just specify format after placeholder like this {0:format}.
Complete example looks like this:
Console.WriteLine("Your account balance is {0:N2}.", value);
Output would be:
Your account balance is 15.34.
All of the options for numeric types are listed here:
http://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx
This seems to work for me (but is hand-rolled):
static string FormatDouble(double d)
{
int maxLen = 13;
double threshold = Math.Pow(10, maxLen);
if (d >= threshold || d <= 0 - (threshold/10))
return "OVERFLOW";
string strDisplay = "" + d;
if (strDisplay.Length > maxLen )
strDisplay = strDisplay.Substring(0, maxLen);
if (strDisplay.EndsWith("."))
strDisplay = strDisplay.Replace(".", "");
return strDisplay;
}
Let me know if it gives you trouble with scientific notation creeping in. I believe the format "{0:R}" should help you avoid that explicitly.
Also, I wasn't sure if you were including +/- sign in digit count or if that was in a separate UI slot.
The theory on rounding here is that, yes, "" + d might round some things, but in general it's going to be many more digits out than are ever displayed so it shouldn't matter. So this method should always truncate.
Here's a solution that does rounding. (I couldn't think of a non-mathematical way to do it):
static string FormatDouble(double d)
{
int maxLen = 13;
int places = (int)Math.Max(Math.Log10(Math.Abs(d)), 0);
places += (d == Math.Abs(d) ? 1 : 2);
if (places > maxLen || places < 1 - maxLen)
return "OVERFLOW";
if (Math.Floor(d) == d) ++places; // no decimal means one extra spot
d = Math.Round(d, Math.Max(maxLen - places - 1, 0));
return string.Format("{0:R}", d);
}
Note: I still think your users might appreciate seeing something closer to what is being stored in the underlying memory than what is often typical of calculators. (I especially hate the ones that can turn 0.99 into 1.01) Either way, you've got at least 3 solutions now so it's up to you.
All began with these simple lines of code:
string s = "16.9";
double d = Convert.ToDouble(s);
d*=100;
The result should be 1690.0, but it's not. d is equal to 1689.9999999999998.
All I want to do is to round a double to value with 2 digit after decimal separator.
Here is my function.
private double RoundFloat(double Value)
{
float sign = (Value < 0) ? -0.01f : 0.01f;
if (Math.Abs(Value) < 0.00001) Value = 0;
string SVal = Value.ToString();
string DecimalSeparator = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
int i = SVal.IndexOf(DecimalSeparator);
if (i > 0)
{
int SRnd;
try
{
// вземи втората цифра след десетичния разделител
SRnd = Convert.ToInt32(SVal.Substring(i + 3, 1));
}
catch
{
SRnd = 0;
}
if (SVal.Length > i + 3)
SVal = SVal.Substring(0, i + 3);
//SVal += "00001";
try
{
double result = (SRnd >= 5) ? Convert.ToDouble(SVal) + sign : Convert.ToDouble(SVal);
//result = Math.Round(result, 2);
return result;
}
catch
{
return 0;
}
}
else
{
return Value;
}
But again the same problem, converting from string to double is not working as I want.
A workaround to this problem is to concatenate "00001" to the string and then use the Math.Round function (commented in the example above).
This double value multiplied to 100 (as integer) is send to a device (cash register) and this values must be correct.
I am using VS2005 + .NET CF 2.0
Is there another more "elegant" solution, I am not happy with this one.
Doubles can't exactly represent 16.9. I suggest you convert it to decimal instead:
string s = "16.9";
decimal m = Decimal.Parse(s) * 100;
double d = (double)m;
You might just want to keep using the decimal instead of the double, since you say you'll be using it for monetary purposes. Remember that decimal is intended to exactly represent decimal numbers that fit in its precision, while double will only exactly represent binary numbers that do.
Math.Round(number, 1)
Edit I got the wrong question - the rounding problems are inherent to a floating point type (float, double). You should use decimal for this.
The best solution for not going be crazy is:
string s = "16.9";
For ,/.
double d = Convert.ToDouble(s.Replace(',','.'),System.Globalization.CultureInfo.InvariantCulture);
For rounding:
Convert.ToDouble((d).ToString("F2"));