tags:

views:

58

answers:

3

I wrote a code for which

if 23E+20 is the input then output should be 230000000(20 zeros)

if 4.456E-14 is the input then 4.456000(14 zeros) should be the output

But its not working properly. Please let me know where I did error. Thank You.

using System;

class test

{

public static void Main()

{

Console.WriteLine("Enter double");

      String ext =Console.ReadLine();



           if(ext.IndexOf("E")!=-1)
        {
           int i=ext.IndexOf("E");

          ext = ext.Substring(0, i);

          for (int j = 0; j < int.Parse(ext.Substring(i + 1, ext.Length - (i + 1))); j++)

          ext = ext + "0";         

          Console.WriteLine(ext);



      }

}   

Console.ReadKey();
}
}
A: 

You are probably going out of bounds of the string, remember always use i-1 index for last letter of array of size i(assuming arrays that start at 0 which is what most languages use). Although it just an educated guess as I don't know C#.

Roman A. Taycher
Also the for loop plus the if (ext.Substring(i, 1) == "E")looks weird isn't there some standard string function that returns the start of a match of a substring?
Roman A. Taycher
ya, I know, Array or string, their index starts from zero.That's why I wrotei<lengthinstead of i<=length
Nani
yes, is there, IndexOf
Nani
What input are you giving it?
Roman A. Taycher
If very big values are multiplied or divided then we get results like 23E+20 , 4.456E-14I need to make these user understandable
Nani
Also whats with all the looping, couldn't you at least loop i till you find E then break and loop j((nested loops aren't good even if they do only a simple comparison each time). Why aren't you using IndexOf then, are you trying to allow numbers like 12E+10E+30?
Roman A. Taycher
I think the other poster is right and string.Format("{?:?}",number) is probably what you want, I'm not sure which one it is the right format, you could try 0 0 like he said.See http://blog.stevex.net/string-formatting-in-csharp/ for more details
Roman A. Taycher
I Tried. It's printing Input as it is.
Nani
That link is Very Useful.Thank You.
Nani
turns out you have to convert the string to a number like String str2=String.Format("{0:0}",Convert.ToInt32(str1));if you leave it a string it ignores numerical formatting.
Roman A. Taycher
A: 

This might be a simpler solution to your problem:

String s = Console.ReadLine();
Double d = Double.Parse(s);
Console.WriteLine(d.ToString("0.#############################################################################"));
Heinzi
A: 

When you substring ext in ext = ext.Substring(0,i) you are assigning ext = "4.456" and cutting away the e-part

when you do ext.Length - (i + 1) in the for loop you get a negative index

Try this instead

int noZeroes = Int32.Parse(ext.Substring(i + 1))
ext = ext.Substring(0, i);
string zeroString = new string('0', noZeroes)

ext += zeroString;
Patrick