[your code here] Rounding real numbers

Justin Whear via Digitalmars-d digitalmars-d at puremagic.com
Fri May 1 10:17:09 PDT 2015


A process for rounding numbers.  This incarnation can be run like
  round 1.23 3.4 4
or by reading lines from stdin.  It could be simplified as an example by 
getting rid of the argument-processing form.  It shows off templated 
function composition using std.functional.pipe, ct-regexes, and component 
programming.
I wrote this after realizing that there wasn't a convenient UNIX utility 
for doing this and use it regularly.

---------------------------------
import std.algorithm,
    std.conv,
    std.functional,
    std.math,
    std.regex,
    std.stdio;

// Transforms input into a real number, rounds it, then to a string
alias round = pipe!(to!real, lround, to!string);

// Matches numbers that look like they need rounding
static reFloatingPoint = ctRegex!`[0-9]+\.[0-9]+`;

void main(string[] args)
{
    // If arguments, process those and exit, otherwise wait around
    //  for input on stdin
    if (args.length > 1)
        args[1..$].map!round.joiner(" ").writeln;
 
    else
        // Replace anything that looks like a real number with the 
        //  rounded equivalent.
        stdin.byLine(KeepTerminator.yes)
             .map!(l => l.replaceAll!(c => c.hit.round)(reFloatingPoint))
             .copy(stdout.lockingTextWriter());
}
---------------------------------


More information about the Digitalmars-d mailing list