d programming, parse or convert string to double
Asked Answered
S

2

9

as easy as it is in other languages, i can't seem to find an option in the d programming language where i can convert a string (ex: "234.32") into a double/float/real.

using atof from the std.c.stdio library only works when i use a constant string. (ex: atof("234.32") works but atof(tokens[i]); where tokens is an dynamic array with strings doesn't work).

how to convert or parse a string into a real/double/float in the d-programming language?

Supertonic answered 26/9, 2012 at 15:51 Comment(0)
C
17

Easy.

import std.conv;
import std.stdio;    

void main() {
    float x = to!float("234.32");
    double y = to!double("234.32");

    writefln("And the float is: %f\nHey, we also got a double: %f", x, y);
}

std.conv is the swiss army knife of conversion in D. It's really impressive!

Curd answered 26/9, 2012 at 15:58 Comment(1)
yep, 'to' is freakin' awesome! :)Mimosa
C
9

To convert from most any type to most any other type, use std.conv.to. e.g.

auto d = to!double("234.32");

or

auto str = to!string(234.32);

On the other hand, if you're looking to parse several whitespace-separated values from a string (removing the values from the string as you go), then use std.conv.parse. e.g.

auto str = "123 456.7 false";

auto i = parse!int(str);
str = str.stripLeft();
auto d = parse!double(str);
str = str.stripLeft();
auto b = parse!bool(str);

assert(i == 123);
assert(d == 456.7);
assert(b == false);
Contingency answered 26/9, 2012 at 17:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.