How to take zero from the decimal part? - c#

I have a senario where I am converting numbers to words and I have suceeded in it, but I found one scenario where it's not working. If I enter the number as "10", it displays "ten". Also, "10.2" will display "ten point two". However, if I enter "10.0" it will not display as "ten point zero".
For seperating the whole number part from the decimal part I usually split the number by '.', but if I enter a number like "10.0", the string array will contain only "10" and not the "0"
The spitting part which I have done is given below:
string[] number = Convert.ToString(context.NumberToTranslate).Split('.');

To test if your number is an integer w/o decimal point you could try and parse it with
int tmpInt;
bool isInteger = Int32.TryParse(num.ToString(), out tmpInt);
If it is an integer just convert the number to your string representation otherwise preserve the digit after the decimal point no matter what using a custom format string:
string number = num.ToString("#.0");
The same issue can arise if your number is less than 1, so you can use the zero placeholder for the digit before the decimal point as well:
string number = num.ToString("#0.0");
Also see Custom Numeric Format Strings

Actually numbers after point is lost if the number, even i the number is a Float or Double.
The solution is to use decimal Type for these numbers, it preserves the 0 after decimal.
Example:
Console.WriteLine(Convert.ToString(10.0M));
Output:
10.0

Febin:
It seems like an order of operations issue. Try doing the splitting before the converting"
var parts = ("10.0").Split('.'); //or context.NumberToTranslate
parts[0] //"10"
parts[1] //"0"
//Convert
string[] number = Convert.ToString(parts);
You don't have to break it out completely, but I did that to show you can split "10.0" and then do what you want with it.

One thing you could do is compare your number to itself cast to an integer to determine if you need to append zero to the string that you're generating.
Something along the lines of:
var n = 10.0f;
if(n == (int)n) {
Console.WriteLine("zero");
}

Related

How to display trailing zeroes?

How do I keep the trailing zeroes like the example below. When I input -.230 with no leading zeroes it only displays -0.23 without the trailing zero. But when I input -0.230 it yields the expected result which is -0.230.
Actual output: -.230 -> -0.23
Expected output: -.230 -> -0.230
I have also tried String.Format("{0:0.000}", n) but it still does not work.
Looks like you are converting to string so you can use the following
someNumber.ToString("N3");
See the MSDN docs for details on how this works, about halfway down the page it also has examples of a bunch of different codes.
It seems that you are print the same number on which you have performed string.format.
Try to store the output of string.format and use that. I have used the same approach that you have used and got the expected answer. Refer following code
var n = -.23;
string str = string.Format("{0:0.000}", n);
Console.WriteLine(str); // This will give you an expected output
Console.WriteLine(n); // This won't give you an expected output
double and decimal mentioned in the question, are quite different types. double is a binary floating point value and it doesn't keep trailing zeroes:
double value = -0.230;
Console.Write(value); // -0.23
Unlike double, decimal being decimal floating-point does store the trailing zeroes:
decimal value = -0.230m; // note suffix "m"
Console.Write(value); // -0.230
When represented as string values of these types can be formatted, e.g. with F3
format string which stands for "3 digits after the decimal point":
double v1 = -0.230;
decimal v2 = -0.230m;
Console.Write($"{v1:f3} {v2:f3}");
Outcome:
-0.230 -0.230

Read input with different datatypes and space seperation

I'm trying to figure out how to write code to let the user input three values (string, int, int) in one line with space to separate the values.
I thought of doing it with String.Split Method but that only works if all the values have the same datatype.
How can I do it with different datatypes?
For example:
The user might want to input
Hello 23 54
I'm using console application C#
Well the first problem is that you need to decide whether the text the user enters itself can contain spaces. For example, is the following allowed?
Hello World, it's me 08 15
In that case, String.Split will not really be helpful.
What I'd try is using a regular expression. The following may serve as a starting point:
Match m = Regex.Match(input, #"^(?<text>.+) (?<num1>(\+|\-)?\d+) (?<num2>(\+|\-)?\d+)$");
if (m.Success)
{
string stringValue = m.Groups["text"].Value;
int num1 = Convert.ToInt32(m.Groups["num1"].Value);
int num2 = Convert.ToInt32(m.Groups["num2"].Value);
}
BTW: The following part of your question makes me frown:
I thought of doing it with String.Split Method but that only works if all the values have the same datatype.
A string is always just a string. Whether it contains a text, your email-address or your bank account balance. It is always just a series of characters. The notion that the string contains a number is just your interpretation!
So from a program's point of view, the string you gave is a series of characters. And for splitting that it doesn't matter at all what the real semantics of the content are.
That's why the splitting part is separate from the conversion part. You need to tell your application that that the first part is a string, the second and third parts however are supposed to be numbers. That's what you need type conversions for.
You are confusing things. A string is either null, empty or contains a sequence of characters. It never contains other data types. However, it might contain parts that could be interpreted as numbers, dates, colors etc... (but they are still strings). "123" is not an int! It is a string containing a number.
In order to extract these pieces you need to do two things:
Split the string into several string parts.
Convert string parts that are supposed to represent whole numbers into a the int type (=System.Int32).
string input = "Abc 123 456"
string[] parts = input.Split(); //Whitespaces are assumed as separators by default.
if (parts.Count == 3) {
Console.WriteLine("The text is \"{0}\"", parts[0]);
int n1;
if (Int32.TryParse(parts[1], out n1)) {
Console.WriteLine("The 1st number is {0}", n1);
} else {
Console.WriteLine("The second part is supposed to be a whole number.");
}
int n2;
if (Int32.TryParse(parts[2], out n2)) {
Console.WriteLine("The 2nd number is {0}", n2);
} else {
Console.WriteLine("The third part is supposed to be a whole number.");
}
} else {
Console.WriteLine("You must enter three parts separated by a space.");
}
What you have to do is get "Hello 23 54" in a string variable. Split by " " and treat them.
string value = "Hello 23 54";
var listValues = value.Split(' ').ToList();
After that you have to parse each item from listValues to your related types.
Hope it helps. ;)

convert to double cutting off zeroes

I have an array that contains product names and prices such as thingy25.00 but when I run this line of code below I get 25 and all zeroes are gone. I need to keep two decimal point after the period so basically 25.00.
price[i] = Convert.ToDouble(product[i].Substring(7, 4));
It will once you format the output like this:
var s = price[i].ToString("#,##0.00");

How do I trim the "0." after I do modulo 1 on a double variable

Hello everyone as the title say I want to trim the "0." after I do modulo 1 on a double variable
Example:
double Number;
Number = Convert.ToDouble(Console.ReadLine()); //12.777
test = Number % 1; //0.777
I want my output to be: 777
only using math with no
string trims and so...
Thank you all !!
and in c# please
That is just a formatting on the ToString. Take a look at all your options here
How about
.ToString(".###");
Without using any string functions!
while(Math.Round(Number-(int)Number,1)!=1)
{
Number=Number/0.1;
if(Number-(int)Number==0)break;//To cover edge case like 0.1 or 0.9
}
NOTE: Number should be of double type!
If I take your question literally, then you do not want the decimal point either, so .ToString(".###") will not get you what you want, unless you remove the first character (which is string manipulation, and you said you don't want that either).
If you want 777 in a numeric variable (not a string), then you can multiply your result by 1000, though I don't know if you'll always have exactly 3 digits after the decimal or not.
The easiest way really is just to use string manipulation. ToString the result without any formatting, then get the substring starting after the decimal. For example:
var x = (.777d).ToString();
var result = x.SubString(x.IndexOf('.') + 1);
You are certainly looking for this:-
.ToString(".###");
As correctly pointed by Marc in comments you should have everything to be in a string, because if you output that 0.777 as it really is stored internally, you'd get 8 random bytes.
Something like this:-
var num = (.777d).ToString();
var result = num.SubString(num.IndexOf('.') + 1);
The most generic way to do this would be:
using System.Globalization;
var provider = NumberFormatInfo.InvariantInfo;
var output = test.ToString(".###", provider)
.Replace(provider.NumberDecimalSeparator, String.Empty);
You can also set the NumberDecimalSeparator on a custom NumberFormatInfo, but if you set it to empty it will throw the exception "Decimal separator cannot be the empty string."

How can I convert string to decimal with trailing zero(s)

Suppose that we have stringvalue=125.32600 when it convert to decimal value with this code
decimal d;
decimal.tryparse(stringvalue,out d)
d value is 125.326
how can I do this convert with final result 125.32600
You cannot because 125.32600 is equal to 125.326. In this case however I guess that you want to print it out with specific format, which can be done like this:
Console.WriteLine(d.ToString("f5"));
Read Standard Numeric Format Strings
UPDATE
Extension method:
public string Format(this decimal source, int precision)
{
if (precision < 0)
{
throw new ArgumentOutOfRangeException("Precision must be a non negative integer");
}
return source.ToString("f" + precision);
}
which can be used like this:
Console.WriteLine(d.Format(5));
Your code works as written (as long as the decimal separator matches your culture):
decimal d;
decimal.TryParse("125.32600", NumberStyles.Number, CultureInfo.InvariantCulture, out d);
s = d.ToString(CultureInfo.InvariantCulture); // 125.32600
Decimal already remembers how many trailing zeros it has. This is caused by decimal representing numbers in non-normalized form, with an integer mantissa and an exponent representing the number of decimal digits. e.g. 125.32600 is represented as 12532600 * 10^-5
The answer is: You can't, at least not like that.
EDIT: correction: decimal already works like that; but you'll still find below a useful way to store your decimals in a DB.
Why? Because that's not how decimals are stored in memory.
Solution: if you need to keep the trailing zeros, just remember the precision explicitly in a separate field (of a class you should create for this purpose); or store the decimals in string form and only convert to decimal as needed.
string strValue = "125.32600";
int precision = strValue.Length - 1; // only the "12332600" part
decimal value = Decimal.Parse(strValue);
stores 8 in precision and 125.326 in value.
To get back the original form:
int afterPt = precision - ((int) value).ToString().Length;
Console.WriteLine(value.ToString("f" + afterPt));
prints
125.32600
P.S. you have to be aware of floating point binary representation issues though, so stuff like 4.05 might be stored as e.g. 4.049999999999999999, so if you need to guarantee this won't happen, use an algorithm that bypasses decimal altogether and uses only integers for storage and computation.
string strValue = "125.32600";
// parse and store
int value = int.Parse(strValue.Replace(".", ""));
int periodIx = strValue.IndexOf(".");
// get back the original representation
string str = value.ToString();
Console.WriteLine(str.Substring(0, periodIx) + "." + str.Substring(periodIx, str.Length - periodIx));
NOTE: Make sure to use , instead of . in locales that need it.
What you can do is count the zeroes in string and then store them in separate DB field. When you want the result with zeroes just concatenate the same no. of zeroes into decimal number string.
ex.
string p="123.456000";
int zeroes=p.Split('0').Length - 1; // guess
decimal value = Decimal.Parse(p); //without zeroes
string valWithZero=value.toString().padRight(zeroes,'0'); //with zeroes
If you really want to have the zeros in the database you could save it as a string, preformatted, but that would be very inefficient.
What is the problem you try to solve by this, there might be a better solution?

Categories

Resources