Question about: ("1.1").to!int;

bachmeier no at spam.net
Fri Oct 23 14:19:54 UTC 2020


On Friday, 23 October 2020 at 13:57:41 UTC, Joseph Rushton 
Wakeling wrote:

> In particular, if `to` just accepted any string numerical 
> representation for conversion to int, how could the caller 
> explicitly _exclude_ non-integer input, if that is their 
> use-case?
>
> So it's far better to require you, as the programmer, to make 
> what you want unambiguous and explicitly write code that will 
> (i) deserialize any numerical string that is acceptable to you 
> and (ii) convert to integer.

Yes, that's the problem, and it doesn't make sense to use a 
statically typed language if the standard library silently 
introduces holes that lead to serious bugs (in this case, loss of 
numerical precision, which can be pretty nasty).

The solution is simple in this case, and it even leads to one 
less character when you're writing your program:

import std;
void main()
{
     int toInt(string s) {
         return(s.to!double.to!int);
     }

     writeln(toInt("1"));
     writeln(toInt("1.1"));
     writeln(toInt("a"));
}


More information about the Digitalmars-d-learn mailing list