Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d programming, parse or convert string to double

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?

like image 454
Marnix v. R. Avatar asked Sep 26 '12 15:09

Marnix v. R.


People also ask

How do you check if a string can be parsed to double?

Therefore, to know whether a particular string is parse-able to double or not, pass it to the parseDouble method and wrap this line with try-catch block. If an exception occurs this indicates that the given String is not pars able to double.

Can we convert string to double in java?

Java Convert String to Double using Double. The valueOf() method of Double wrapper class in Java, works similar to the parseDouble() method that we have seen in the above java example. Lets see the complete example of conversion using Double. valueOf(String) method.

Which one of the following methods would you use to convert a string to a double?

There are three ways to convert a String to double value in Java, Double. parseDouble() method, Double. valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time.


2 Answers

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!

like image 58
dav1d Avatar answered Oct 07 '22 04:10

dav1d


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);
like image 43
Jonathan M Davis Avatar answered Oct 07 '22 04:10

Jonathan M Davis