double To string as Java
От: Аноним  
Дата: 29.07.10 09:57
Оценка:
Возникла необходимость конвертировать число в строку и обратно по правилам Java. Есть ли какие-нибудь уже готовые библиотеки?
Re: double To string as Java
От: Кодт Россия  
Дата: 29.07.10 10:02
Оценка:
Здравствуйте, Аноним, Вы писали:

А>Возникла необходимость конвертировать число в строку и обратно по правилам Java. Есть ли какие-нибудь уже готовые библиотеки?


А какие правила у явы? Они чем-то отличаются от обычной десятичной записи?
Если не отличаются, то обычный sprintf / sscanf спасёт отца русской демократии.
Перекуём баги на фичи!
Re[2]: double To string as Java
От: Pavel Dvorkin Россия  
Дата: 29.07.10 10:07
Оценка:
Здравствуйте, Кодт, Вы писали:

К>Здравствуйте, Аноним, Вы писали:


А>>Возникла необходимость конвертировать число в строку и обратно по правилам Java. Есть ли какие-нибудь уже готовые библиотеки?


К>А какие правила у явы? Они чем-то отличаются от обычной десятичной записи?

К>Если не отличаются, то обычный sprintf / sscanf спасёт отца русской демократии.

Лучше все же strto(l,d), там можно проверить успешность преобразования и определить причину неудачи.
With best regards
Pavel Dvorkin
Re[2]: double To string as Java
От: Аноним  
Дата: 29.07.10 10:15
Оценка:
К>А какие правила у явы?

public static String toString(float f)
Returns a String representation for the specified float value. The argument is converted to a readable string format as follows. All characters and characters in strings mentioned below are ASCII characters.
If the argument is NaN, the result is the string "NaN".
Otherwise, the result is a string that represents the sign and magnitude (absolute value) of the argument. If the sign is negative, the first character of the result is '-' ('-'); if the sign is positive, no sign character appears in the result. As for the magnitude m:
If m is infinity, it is represented by the characters "Infinity"; thus, positive infinity produces the result "Infinity" and negative infinity produces the result "-Infinity".
If m is zero, it is represented by the characters "0.0"; thus, negative zero produces the result "-0.0" and positive zero produces the result "0.0".
If m is greater than or equal to 10-3 but less than 107, then it is represented as the integer part of m, in decimal form with no leading zeroes, followed by '.' (.), followed by one or more decimal digits representing the fractional part of m.
If m is less than 10-37, then it is represented in so-called "computerized scientific notation." Let n be the unique integer such that 10n<=m<1; then let a be the mathematically exact quotient of m and 10n so that 1<a&lt10. The magnitude is then represented as the integer part of a, as a single decimal digit, followed by '.' (.), followed by decimal digits representing the fractional part of a, followed by the letter 'E' (E), followed by a representation of n as a decimal integer, as produced by the method Integer.toString(int) of one argument.
How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type float. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument f. Then f must be the float value nearest to x; or, if two float values are equally close to xthen f must be one of them and the least significant bit of the significand of f must be 0.
Parameters:
f — the float to be converted.
Returns:
a string representation of the argument.
Re[3]: double To string as Java
От: Кодт Россия  
Дата: 29.07.10 12:45
Оценка:
Здравствуйте, Аноним, Вы писали:

К>>А какие правила у явы?


A>Returns a String representation for the specified float value. The argument is converted to a readable string format as follows.


Ну что ж, действуем "as follows".
Каркас вот такой.
double Mantissa(double x)
{
  while(x > -0.1 && x < 0.1) x *= 10;
  while(x < -10. || x > 10.) x /= 10;
  return x;
}
int FracLen(double x)
{
  ????? // сходу не придумал красивый алгоритм...
}

string ToString(double x)
{
  switch(_fpclass(x))
  {
  case _FPCLASS_SNAN:
  case _FPCLASS_QNAN:
    return "NaN";

  case _FPCLASS_PINF:
    return "Inifinity";
  case _FPCLASS_NINF:
    return "-Infinity";

  case _FPCLASS_PZ:
    return "0.0";
  case _FPCLASS_NZ:
    return "-0.0";

  default:
    {
      char buf[_CVTBUFSIZE+1];
      if(fabs(x)>=1e-3 && fabs(x)<=1e7)
      {
        // фиксированный формат (%f)
        sprintf(buf, "%.*f", FracLen(x), x);
      }
      else
      {
        // плавающий формат (%e)
        sprintf(buf, "%.*e", FracLen(Mantissa(x)), x);
      }
      return string(buf);
    }
  }
}
Перекуём баги на фичи!
Re[4]: double To string as Java
От: Аноним  
Дата: 29.07.10 13:36
Оценка:
Спасибо за пример. То есть вы предлагаете "быстренько" запрограммировать? А кто тесты будет писать? Последнее пугает больше, чем сама реализация.
Я мечтал, что кто-то скажет — вот референс реализация явы на си плюс плюс и юнит тестами...
Re[5]: double To string as Java
От: Oleg Kosenkov США http://files.rsdn.org/4543/rsdn.gif
Дата: 29.07.10 15:14
Оценка:
Здравствуйте, Аноним, Вы писали:

А>Спасибо за пример. То есть вы предлагаете "быстренько" запрограммировать? А кто тесты будет писать? Последнее пугает больше, чем сама реализация.

А>Я мечтал, что кто-то скажет — вот референс реализация явы на си плюс плюс и юнит тестами... ;-)

в этом случае можно взять референсные исходники JVM и сделать реализацию по образу и подобию.
my $.02
Re[6]: double To string as Java
От: Аноним  
Дата: 29.07.10 15:47
Оценка:
OK>в этом случае можно взять референсные исходники JVM и сделать реализацию по образу и подобию.
Если бы вы еще написали, где взять, цены бы вашему посту не было бы.
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.