How to take zero from the decimal part?
I have a senario where I am converting numbers to words and I hav开发者_StackOverflow中文版e 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");
}
精彩评论