Return the complete number

Simen Kjærås simen.kjaras at gmail.com
Wed Jul 24 21:02:11 UTC 2019


On Wednesday, 24 July 2019 at 16:16:15 UTC, Greatsam4sure wrote:
> On Wednesday, 24 July 2019 at 15:57:06 UTC, a11e99z wrote:
>> On Wednesday, 24 July 2019 at 15:56:13 UTC, a11e99z wrote:
>>> On Wednesday, 24 July 2019 at 15:45:08 UTC, Greatsam4sure 
>>> wrote:
>>>> int main(){
>>>>  double mum = 0;
>>>>  Write("enter a number: ")
>>>>  readf(" %s\n",&num);
>>>>  Writeln(num);
>>>>
>>>> }
>>>>
>>>> How do I return the complete number the user enter since I 
>>>> don't since the user can enter numbers of various length 
>>>> with dmd approximating it.
>>>>
>>>> I will appreciate any help
>>>
>>>   readf!" %s\n"( num );
>>> or
>>>   num.readf!" %s\n";
>>> or
>>>   num = readln.strip.to!double;
>
>       writeln(num)
>
> The result is always to six significant figure. I want the 
> whole number to be diaplay

So, there are several possible issues here. First, floating-point 
numbers have limited precision - a double can not correctly 
represent all integers above 2^52, for instance. That's 4.5 
quadrillion though, so rarely an issue. In your case, as others 
have commented, writefln with a correctly chosen format string[1] 
will do the trick.

However, what is the correctly chosen format string? This is a 
very hard question to answer, as it depends on what number was 
typed, and what you mean by 'the complete number the user enter'. 
While drug's suggestion of "%.16f" will return an accurate 
representation of the floating-point number, it will include a 
lot of trailing zeroes that were presumably not present in the 
input string. It will also expose floating-point's limitations 
when presented with huge numbers, like 1e23 will print 
99999999999999991603000.0000000000000000. The best option might 
be "%.16g", which will choose the shortest of the scientific 
notation and the regular notation, as well as strip trailing 
zeroes. Depending on the criteria though, this might still not be 
the optimal solution.

--
   Simen


1: https://dlang.org/phobos/std_format.html#format-string


More information about the Digitalmars-d-learn mailing list