user7039610
user7039610

Reputation:

How to turn a floating point number into a string in ATS?

Basically, I am looking for a function of the following interface:

fun double2string(x: double): string

which converts a double into a string representation for it. For instance, double2string(3.14) should return "3.14".

Upvotes: 2

Views: 100

Answers (4)

Hongwei Xi
Hongwei Xi

Reputation: 935

Here is a quick way to do it:

fun
double2string
(
x0: double
) : string = let
  val i0 = g0float2int_double_int(x0)
  val d0 = g0float2int_double_int(100000000 * (x0 - i0))
  val i0_rep = g0int2string(i0)
  val d0_rep = g0int2string(d0)
  val x0_rep =
  string0_append3
    ($UNSAFE.strptr2string(i0_rep), ".", $UNSAFE.strptr2string(d0_rep))
  // end of [val]                                                                                                          
  val ((*freed*)) = strptr_free(i0_rep)
  val ((*freed*)) = strptr_free(d0_rep)
in
  strptr2string(x0_rep)
end // end of [double2string]      

Upvotes: 0

Hongwei Xi
Hongwei Xi

Reputation: 935

For compiling to JavaScript, 'String' can be called to do this. Actually, 'String' turns any given object into some form string representation for it.

Upvotes: 0

Hongwei Xi
Hongwei Xi

Reputation: 935

There is a function of the name atspre_string_make_snprintf in ATSLIB for constructing strings. For instance, one can do:

#include
"share/atspre_staload.hats"

fun
double2string(x: double): string =
$extfcall
(
  string, "atspre_string_make_snprintf", "%.8e", x
) (* double2string *)

implement
main0() =
println! ("Pi = ", double2string(3.1415926535))

What is returned by atspre_string_make_snprintf is a linear string (strptr), which can be freed:

fun double2strptr(x: double): Strptr1 = $extfcall(...)

When compiling, please remember to pass the flag -latslib. You can try this example on-line:

https://glot.io/snippets/ejm6ous1fh

Upvotes: 0

masterq
masterq

Reputation: 81

Sometimes I choose following cheat:

#include "share/atspre_define.hats"
#include "share/atspre_staload.hats"

%{^
#include <assert.h>

char *double2string(double x) {
#define DECIMAL        8
#define DECIMAL_FORMAT "%.8e"
#define DECIMAL_LEN    DECIMAL+2+5
  char *s = malloc(DECIMAL_LEN+1);
  assert(NULL != s);
  memset(s, 0, DECIMAL_LEN+1);

  snprintf(s, DECIMAL_LEN, DECIMAL_FORMAT, x);
  return s;
}
%}

extern fun double2string (x: double): strptr = "mac#"

implement main0 () = {
  val s = double2string 1234567890.1234567890
  val () = println! s
  val () = free s
}

Upvotes: 1

Related Questions