[Haskell-beginners] How to convert a float or double number into a string?
Oscar Benjamin
oscar.j.benjamin at gmail.com
Thu Sep 19 00:46:27 CEST 2013
On 18 September 2013 16:07, yi lu <zhiwudazhanjiangshi at gmail.com> wrote:
> You are right! I hope to input a number, for example 123, and output its
> text "one hundred and twenty-three".
> So, for 1.23456789012345678901, I want the result is "one point two three
> four five six ...(something omitted)".
You should probably explain this at the beginning!
> I can define a funciton, say "toText", to preform this action.
> In ghci, I can use like this.
> Prelude>toText 123.45
> "one hundred and twenty-three point four five"
>
> However, in this function, I have to read this number as String(originally a
> number, now "123"), and make it to words(String) like "one two three".
> But for a float number, it will not work very well.
> Prelude>toText 1.23456789012345678901
> "(a truncated answer)"
>
> This confuses me!
I suspect you don't yet understand what a float really is:
http://en.wikipedia.org/wiki/Single-precision_floating-point_format
If you do understand what a single (or double) precision float is then
consider this: most values cannot be exactly represented by the float
type. When you ask Haskell to create a float with some value given as
a decimal string it will usually not return a float with the exact
value you asked for since this is often impossible. Instead it will
only promise to give you a "close" value.
For your problem I would just use string manipulation. Testing for
n<1000000 is just as easy as testing the length of a decimal string.
Conversion to float or Rational is usually only worthwhile if you're
intending to do some arithmetic which you're not. So your input is a
string your output should be a string and you're not doing arithmetic:
you may as well view this as a text processing problem and just write
functions that work with strings.
Oscar
More information about the Beginners
mailing list