简体   繁体   English

Float.toString()和Integer.toString()如何工作?

[英]how does Float.toString() and Integer.toString() works?

How can i implement an algorithm to convert float or int to string? 如何实现将float或int转换为字符串的算法? I found one link http://geeksforgeeks.org/forum/topic/amazon-interview-question-for-software-engineerdeveloper-0-2-years-about-algorithms-13 我找到了一个链接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: 数字0-9在大多数字符编码中是顺序的,因此与它的整数值一起使用将有助于解决问题:

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 注意, "" + x的技术实际上被重写为类似

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. 因此,不要以为所写的内容是100%精确地完成了它,而是将其视为必须从更大的角度看待的事情。

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. 然后将数字除以10,然后重复...,直到剩下零为止。

Of course, it is a bit more complicated than that, especially in the float case. 当然,它要比这复杂得多,尤其是在float情况下。


if i have a single digit in int fomrat then i need to insert it into char , how to convert int to char? 如果我在int fomrat中有一位数字,那么我需要将其插入char中,如何将int转换为char?

Easy: 简单:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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