substitute the number after decimal with 0 - c#

How do I replace the decimal part of currency with 0's
Here's my cuurency: 166.7
This is to be formatted as 000000016670
The length of this field is 12.
s.padright(12,0); This is will the second part I believe.
The first part will involve replace the number after the decimal with 000..
Thanks

You can multiply by 100 then format the number.
var num = 166.7;
var numString = (num * 100).ToString("000000000000");
Multiplying by 100 turns 166.7 to 16670. Next you need to pad the left part of the number, which is what the ToString does. Each 0 represents a digit. It means, write the number that belongs to that digit, and if no number is present print 0.

Related

Will converting Char.GetNumericValue() to int destroy information?

I am implementing GetHashCode(). I want to sum the values in a property called string Id then divide
by some constant and return the result. I am using GetNumericValue():
int sum = 0;
foreach (var ch in Id)
sum += char.GetNumericValue(ch);
But it seems that GetNumericValue returns double. is it ok to convert it into an int?
I thought that Unicode characters are represented by whole number, why is double returned?
And is it okay to ignore it?
Why is double returned?
While 0-9 are the standard digits, actually there are some Unicode characters that represent numbers, some of them are floating point like ⅔ or ½. Let's get an example:
var ch = char.GetNumericValue('½');
Console.WriteLine(ch);// 0.5 output
Yes, it will lose data for some values, since this is the numerical value of unicode characters that are themselves numbers - and unicode includes characters that are non-integer numbers:
var val = char.GetNumericValue('½'); // or ¼, or ꠲, or ⳽
System.Console.WriteLine(val);

String to Decimal with 2 decimal places always

I have a string that is to be converted to decimal. The string could be entered with no decimal places e.g. "123" or 2 decimal places, e.g. "123.45" or somewhat awkwardly, 1 decimal place "123.3". I want the number displayed (the Property invoice.Amount which is type decimal) with 2 decimal places. The code below does that. I think it could be written better though. How?
decimal newDecimal;
bool isDecimal = Decimal.TryParse(InvoiceDialog.InvoiceAmount, out newDecimal);
string twoDecimalPlaces = newDecimal.ToString("########.00");
invoice.Amount = Convert.ToDecimal(twoDecimalPlaces);
In part, I don't understand, for the string formatting "########.00", what # does and what 0 does. E.g. how would it be different if it were "########.##"?
# is an optional digit when 0 is a mandatory digit
For instance
decimal d = 12.3M;
// d with exactly 2 digits after decimal point
Console.WriteLine(d.ToString("########.00"));
// d with at most 2 digits after decimal point
Console.WriteLine(d.ToString("########.##"));
Outcome:
12.30 // exactly 2 digits after decimal point: fractional part padded by 0
12.3 // at most 2 digits after decimal point: one digit - 3 - is enough
Basically, # means optional, where as 0 is mandatory.
As for better explanation, if you put # then if number is available to fullfil the placeholder it'll be added if not it'll be ignored.
Putting 0 however is different as it'll always put a value in for you.
You can combine the two together.
String.Format("{0:0.##}", 222.222222); // 222.22
String.Format("{0:0.##}", 222.2); // 222.2
String.Format("{0:0.0#}", 222.2) // 222.2
The "#" is optional while the "0" will show either the number or 0.
For example,
var x = 5.67;
x.ToString("##.###"); // 5.67
x.ToString("00.000"); // 05.670
x.ToString("##.##0"); // 5.670
If you just care about how many decimal places you have, I would recommend using
x.ToString("f2"); // 5.67
to get 2 decimal spots.
More information can be found at http://www.independent-software.com/net-string-formatting-in-csharp-cheat-sheet.html/.
You don't need to convert the decimal to string to do the formatting for 2 decimal places. You can use the decimal.Round method directly. You can read about it here.
So your code can be converted to
decimal newDecimal;
Decimal.TryParse(s, out newDecimal);
newDecimal = decimal.Round(newDecimal, 2, MidpointRounding.AwayFromZero);
The above code also be simplified with C# 7.0 declaration expression as
Decimal.TryParse(s, out decimal newDecimal);
newDecimal = decimal.Round(newDecimal, 2, MidpointRounding.AwayFromZero);
Now newDecimal will have have a value with 2 precision.
You can check this live fiddle.

3 digit hexadecimal generator for Access Database

I am trying to figure out how to create a hexadecimal generator that always spits out 3 digits in C# and sends it to my access database. Here is the code that I found an example of on here and changed a little bit, but the generator sometimes only gives me 2 digits. What am I doing wrong?
Thank you,
var r = new Random();
int A = r.Next(100, 500);
string hexValue1 = A.ToString("X");
MessageBox.Show(hexValue1);
As described in
The Hexadecimal ("X") Format Specifier
The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.
So you can simply use
string hexValue1 = A.ToString("X3");
to always give you three digits (provided that A <= 0xFFF)..
The minimum possible value for a 3 digit hex value would be 0x100 (256 decimal) and the maximum value would be 0xFFF (4095 decimal). So in order to generate this string you need to use something like:
var r = new Random();
int A = r.Next(256, 4096); //Using the exclusive maximum (required max + 1)
string hexValue1 = A.ToString("X");
MessageBox.Show(hexValue1);

System.Double value with max characters

I'm testing net xml serialization of double[] arrays so I'm interested to know whats the double value that has most characters int it's serialized for so I can test whats the max output size of serialized array.
It should be 24.
double.MinValue.ToString("R").Length
From double.ToString(string)
or "R", which returns 15 digits if the number can be represented with that precision or 17 digits if the number can only be represented with maximum precision.
you have that there are at max 17 digits, plus 1 for sign, plus 1 for the decimal separator, plus 5 for the E+xxx (double.MaxValue is 1.7976931348623157E+308 and double.Epsilon, the smallest value > 0, is 4.94065645841247E-324, so both in the form E[+-][0-9]{1,3}).
Note that technically, in some strange languages,
var str2 = double.PositiveInfinity.ToString("R");
could be longer (because the string is localized), but I hope you'll serialize your numbers with CultureInfo.InvariantCulture!
But remember that users could have changed their culture from the control panel... something like:
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NegativeSign = "Negative";
culture.NumberFormat.NumberDecimalSeparator = "DecimalSeparator";
var str4 = double.MinValue.ToString("R", culture);
Result: Negative1DecimalSeparator7976931348623157E+308
For this reason it's better to use the CultureInfo.InvariantCulture :-)
But if you want to know the truth, in the Control Panel the decimal separator can be long up to 3 characters, and the negative sign up to 4 (you can try it, or you can check the LOCALE_SDECIMAL and LOCALE_SNEGATIVESIGN, clearly the terminating null character can be ignored in .NET)
You can try -1.0 / 3.0, it will have many decimals.

Best way to get whole number part of a Decimal number

What is the best way to return the whole number part of a decimal (in c#)? (This has to work for very large numbers that may not fit into an int).
GetIntPart(343564564.4342) >> 343564564
GetIntPart(-323489.32) >> -323489
GetIntPart(324) >> 324
The purpose of this is: I am inserting into a decimal (30,4) field in the db, and want to ensure that I do not try to insert a number than is too long for the field. Determining the length of the whole number part of the decimal is part of this operation.
By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).
If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:
Math.Truncate(number)
and return the value as... A DECIMAL or a DOUBLE.
edit: Truncate is definitely the correct function!
I think System.Math.Truncate is what you're looking for.
Depends on what you're doing.
For instance:
//bankers' rounding - midpoint goes to nearest even
GetIntPart(2.5) >> 2
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -6
or
//arithmetic rounding - midpoint goes away from zero
GetIntPart(2.5) >> 3
GetIntPart(5.5) >> 6
GetIntPart(-6.5) >> -7
The default is always the former, which can be a surprise but makes very good sense.
Your explicit cast will do:
int intPart = (int)343564564.5
// intPart will be 343564564
int intPart = (int)343564565.5
// intPart will be 343564566
From the way you've worded the question it sounds like this isn't what you want - you want to floor it every time.
I would do:
Math.Floor(Math.Abs(number));
Also check the size of your decimal - they can be quite big, so you may need to use a long.
You just need to cast it, as such:
int intPart = (int)343564564.4342
If you still want to use it as a decimal in later calculations, then Math.Truncate (or possibly Math.Floor if you want a certain behaviour for negative numbers) is the function you want.
I hope help you.
/// <summary>
/// Get the integer part of any decimal number passed trough a string
/// </summary>
/// <param name="decimalNumber">String passed</param>
/// <returns>teh integer part , 0 in case of error</returns>
private int GetIntPart(String decimalNumber)
{
if(!Decimal.TryParse(decimalNumber, NumberStyles.Any , new CultureInfo("en-US"), out decimal dn))
{
MessageBox.Show("String " + decimalNumber + " is not in corret format", "GetIntPart", MessageBoxButtons.OK, MessageBoxIcon.Error);
return default(int);
}
return Convert.ToInt32(Decimal.Truncate(dn));
}
Very easy way to separate value and its fractional part value.
double d = 3.5;
int i = (int)d;
string s = d.ToString();
s = s.Replace(i + ".", "");
s is fractional part = 5 and
i is value as integer = 3
Public Function getWholeNumber(number As Decimal) As Integer
Dim round = Math.Round(number, 0)
If round > number Then
Return round - 1
Else
Return round
End If
End Function
Forgetting the meaning of the term: "Whole Number" seems common in the answers, and in the Question.
Getting the whole number from the number: 4 is simple:
1 x 4 = 4 <- A Whole Number! The first Whole Number!
2 x 4 = 8 <- A Whole Number!
3 x 4 = 12 <- A Whole Number!
Rounding a Number, to get a Whole Number is a cheats method of getting the Whole Numbers! Rounding it removing the Non-Whole Number part of the Number!
1.3 x 4 = 5.2 <- NOT a Whole Number!
1 x 343564564.4342 <- NOT a Whole Number!
Its important to understand what a Whole Number is!
4 / 1 = 4 <- A Whole Number!
4 / 2 = 2 <- A Whole Number!
4 / 3 = 1.333 recurring <- NOT A Whole Number!
Please ask, and answer the questions with a bit more Accuracy Peeps...
double A = Math.Abs(343564564.4342);
double B = Math.Floor(343564564.4342);
double C = Math.Ceiling(343564564.4342);
double D = Math.Truncate(343564564.4342);
Returns:
A = 343564564.4342
B = 343564564
C = 343564565
D = 343564564
or:
double E = Math.Round(343564564.4342, 0);
E = 343564564
Is a Mathematical Function, thus changing the Number, and not working with Whole Numbers. Your Rounding Non-Whole Numbers!

Categories