简体   繁体   中英

how does Float.toString() and Integer.toString() works?

How can i implement an algorithm to convert float or int to string? I found one link http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-0-2-years-about-algorithms-13

but i cant understand the algorithm given there

the numbers 0-9 are sequential in most character encoding so twiddling with the integral value of it will help here:

int val;
String str="";
while(val>0){
    str = ('0'+(val%10)) + str;
    val /= 10;
}

Here's a sample of how to do the integer to string, from it I hope you'll be able to figure out how to do the float to string.

public String intToString(int value) {
  StringBuffer buffer = new StringBuffer();
  if (value < 0) {
    buffer.append("-");
  }
  // MAX_INT is just over 2 billion, so start by finding the number of billions.
  int divisor = 1000000000;
  while (divisor > 0) {
    int digit = value / divisor;  // integer division, so no remainder.
    if (digit > 0) {
      buffer.append('0'+digit);
      value = value - digit * divisor; // subtract off the value to zero out that digit.
    }
    divisor = divisor / 10; // the next loop iteration should be in the 10's place to the right
  }
}

This is of course, very unoptimized, but it gives you a feel for how the most basic formatting is accomplished.

Note that the technique of "" + x is actually rewritten to be something like

StringBuffer buffer = new StringBuffer();
buffer.append("");
buffer.append(String.valueOf(x));
buffer.toString();

So don't think that what is written is 100% exactly HOW it is done, look at is as what must happen in a larger view of things.

The general idea is to pick off the least significant digit by taking the number remainder ten. Then divide the number by 10 and repeat ... until you are left with zero.

Of course, it is a bit more complicated than that, especially in the float case.


if i have a single digit in int fomrat then i need to insert it into char , how to convert int to char?

Easy:

int digit = ... /* 0 to 9 */
char ch = (char)('0' + digit);

好了,您可以自己阅读代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM