Formatted numeric output

From Rosetta Code

(Redirected from Formatted Numeric Output)
Jump to: navigation, search
Task
Formatted numeric output
You are encouraged to solve this task according to the task description, using any language you may know.

Express a number in decimal as a fixed-length string with leading zeros.

For example, the number 7.125 could be expressed as "00007.125".

Contents

[edit] Ada

with Ada.Text_Io.Editing; use Ada.Text_Io.Editing;
with Ada.Text_Io; use Ada.Text_Io;
 
procedure Zero_Fill is
Pic_String: String := "<999999.99>";
Pic : Picture := To_Picture(Pic_String);
type Money is delta 0.01 digits 8;
package Money_Output is new Decimal_Output(Money);
use Money_Output;
 
Value : Money := 37.25;
begin
Put(Item => Value, Pic => Pic);
end Zero_Fill;

The output of this program is

000037.25

[edit] ALGOL 68

Translation of: C

Works with: ALGOL 68 version Revision 1 - no extensions to language used

Works with: ALGOL 68G version Any - tested with release 1.18.0-9h.tiny

main:(
REAL r=exp(pi)-pi;
print((r,newline));
printf(($g(-16,4)l$,-r));
printf(($g(-16,4)l$,r));
printf(($g( 16,4)l$,r));
printf(($g( 16,4,1)l$,r));
printf(($-dddd.ddddl$,-r));
printf(($-dddd.ddddl$,r));
printf(($+dddd.ddddl$,r));
printf(($ddddd.ddddl$,r));
printf(($zzzzd.ddddl$,r));
printf(($zzzz-d.ddddl$,r));
printf(($zzzz-d.ddddedl$,r));
printf(($zzzz-d.ddddeddl$,r));
printf(($4z-d.4de4dl$,r))
)

Output:

+1.99990999791895e  +1
        -19.9991
         19.9991
        +19.9991
+19999099.979e-6
-0019.9991
 0019.9991
+0019.9991
00019.9991
00019.9991
    19.9991
     1.9999e1
     1.9999e01
     1.9999e0001

[edit] AmigaE

The function RealF can be used to convert a floating point value into a string, with a specified number of decimal digits. But to fit the string into a greater container prepending 0 we must write our own function. (The one here proposed has no a flag for the alignment of the result inside the containing string)

PROC newRealF(es, fl, digit, len=0, zeros=TRUE)
DEF s, t, i
IF (len = 0) OR (len < (digit+3))
RETURN RealF(es, fl, digit)
ELSE
s := String(len)
t := RealF(es, fl, digit)
FOR i := 0 TO len-EstrLen(t)-1 DO StrAdd(s, IF zeros THEN '0' ELSE ' ')
StrAdd(s, t)
StrCopy(es, s)
DisposeLink(s)
DisposeLink(t)
ENDIF
ENDPROC es
 
PROC main()
DEF s[100] : STRING
WriteF('\s\n', newRealF(s, 7.125, 3,9))
ENDPROC

[edit] APL

      'ZF15.9' ⎕FMT 7.125
00007.125000000

APL's ⎕FMT is similar to C's printf (only it operates on arrays).

[edit] AWK

BEGIN {
r=7.125
printf " %9.3f\n",-r
printf " %9.3f\n",r
printf " %-9.3f\n",r
printf " %09.3f\n",-r
printf " %09.3f\n",r
printf " %-09.3f\n",r
}

Same output as the C code.

[edit] AutoHotkey

contributed by Laszlo on the ahk forum

MsgBox % pad(7.25,7)  ; 0007.25
MsgBox % pad(-7.25,7) ; -007.25
 
pad(x,len) { ; pad with 0's from left to len chars
IfLess x,0, Return "-" pad(SubStr(x,2),len-1)
VarSetCapacity(p,len,Asc("0"))
Return SubStr(p x,1-len)
}

[edit] C#

 
class Program
{
 
 
static void Main(string[] args)
{
 
float myNumbers = 7.125F;
 
string strnumber = Convert.ToString(myNumbers);
 
Console.WriteLine(strnumber.PadLeft(9, '0'));
 
Console.ReadLine();
}
 
 
 
 
}
 

[edit] C

#include <stdio.h>
main(){
float r=7.125;
printf(" %9.3f\n",-r);
printf(" %9.3f\n",r);
printf(" %-9.3f\n",r);
printf(" %09.3f\n",-r);
printf(" %09.3f\n",r);
printf(" %-09.3f\n",r);
return 0;
}

Output:

   -7.125
    7.125
7.125    
-0007.125
00007.125
7.125  

[edit] C++

#include <iostream>
#include <iomanip>
 
int main()
{
std::cout << std::setfill('0') << std::setw(9) << std::fixed << std::setprecision(3) << 7.125 << std::endl;
return 0;
}

[edit] Clojure

Translation of: Common Lisp Using cl format strings

(cl-format true "~9,3,,,'0F" 7.125)

Translation of: java Using java format strings

(printf "%09.3f" 7.125) ; format works the same way (without side the effect of printing)

[edit] Common Lisp

(format t "~9,3,,,'0F" 7.125)

[edit] Eiffel

Works with: Eiffel Studio version 6.6

 
note
description : "{
2 Examples are given.
The first example uses the standard library's FORMAT_DOUBLE class.
The second example uses the AEL_PRINTF class from the freely available
Amalasoft Eiffel Library (AEL).
 
See additional comments in the code.
}"

 
class APPLICATION
 
inherit
AEL_PRINTF -- Optional, see below
 
create
make
 
feature {NONE} -- Initialization
 
make
-- Run application.
do
print_formatted_std (7.125)
print_formatted_ael (7.125)
end
 
--|--------------------------------------------------------------
 
print_formatted_std (v: REAL_64)
-- Print the value 'v' as a zero-padded string in a fixed
-- overall width of 9 places and, with a precision of
-- to 3 places to the right of the decimal point.
-- Use the FORMAT_DOUBLE class from the standard library
local
fmt: FORMAT_DOUBLE
do
create fmt.make (9, 3)
fmt.zero_fill
print (fmt.formatted (v) + "%N")
end
 
--|--------------------------------------------------------------
 
print_formatted_ael (v: REAL_64)
-- Print the value 'v' as a zero-padded string in a fixed
-- overall width of 9 places and, with a precision of
-- to 3 places to the right of the decimal point.
-- Use the AEL_PRINTF class from the Amalasoft Eiffel Library
-- freely available from www.amalasoft.com
do
-- printf accepts a format string and an argument list
-- The argument list is a container (often a manifest
-- array) of values corresponding to the type of the format
-- specified in the format string argument.
-- When only one argument is needed, then there is also the
-- option to use just the value, without the container.
-- In this example, the line would be:
-- printf ("%%09.3f%N", v)
-- The more deliberate form is used in the actual example,
-- as it is more representative of common usage, when there
-- are multiple value arguments.
 
printf ("%%09.3f%N", << v >>)
end
 
end
 

[edit] Forth

Forth has a rather rich set of number formatting words, which makes formatted output very flexible but sometime cumbersome.

Here one way to generate the required output. Note that the number generated is NOT truncated to the field width. If you wish to truncate the number, remove #s and 1- from the definition. (The 1- is necessary because #s always generates at least one digit, even if it's zero.)

\ format 'n' digits of the double word 'd'
: #n ( d n -- d ) 0 ?do # loop ;
 
\ ud.0 prints an unsigned double
: ud.0 ( d n -- ) <# 1- #n #s #> type ;
 
\ d.0 prints a signed double
: d.0 ( d n -- ) >r tuck dabs <# r> 1- #n #s rot sign #> type ;

Usage example:

Type:    123 s>d  8 ud.0
Result: 00000123 ok
Type: -123 s>d 8 d.0
Result: -00000123 ok

[edit] Fortran

Works with: Fortran version 90 and later Using standard data edit descriptors it is only possible to precede Integer data with leading zeros.

INTEGER :: number = 7125
WRITE(*,"(I8.8)") number ! Prints 00007125

[edit] gnuplot

print sprintf("%09.3f", 7.125)

[edit] Go

fmt.Printf("%09.3f", 7.125)

[edit] Haskell

import Text.Printf
main =
printf "%09.3f" 7.125

[edit] HicEst

WRITE(ClipBoard, Format='i5.5, F4.3') INT(7.125), MOD(7.125, 1)    ! 00007.125 

[edit] IDL

n = 7.125
print, n, format='(f08.3)'
;==> 0007.125

[edit] J

   'r<0>9.3' (8!:2) 7.125
00007.125

Documentation on 8!:

[edit] Java

Works with: Java version 1.5+ Stealing printf from C/C++:

public class Printing{
public static void main(String[] args){
double printer = 7.125;
System.out.printf("%09.3f",printer);//System.out.format works the same way
}
}

[edit] JavaScript

var n = 123;
var str = ("00000" + n).slice(-5);
alert(str);

or, put in browser URL: javascript:n=123;alert(("00000"+n).slice(-5));

Also, a 60-line implementation of sprintf can be found here.

[edit] Logo

Various collection functions, such as MAP and FILTER, will work on individual characters of a string when given a word instead of a list.

to zpad :num :width :precision
output map [ifelse ? = "| | ["0] [?]] form :num :width :precision
end
print zpad 7.125 9 3  ; 00007.125

Works with: UCB Logo As a debugging feature, you can drop down to C language printf formatting by giving -1 for the width and a format string for the precision.

print form 7.125 -1 "|%09.3f|    ; 00007.125

[edit] Lua

function digits(n) return math.floor(math.log(n) / math.log(10))+1 end
function fixedprint(num, digs) --digs = number of digits before decimal point
for i = 1, digs - digits(num) do
io.write"0"
end
print(num)
end
 
fixedprint(7.125, 5) --> 00007.125

[edit] Modula-3

Modules IO and Fmt must be imported before use.

IO.Put(Fmt.Pad("7.125\n", length := 10, padChar := '0'));

[edit] Oberon-2

Module Out must be imported before use.

Out.Real(7.125, 9, 0);

[edit] Objective-C

NSLog(@"%09.3f", 7.125);

or

NSLog(@"%@", [NSString stringWithFormat:@"%09.3f", 7.125]);

[edit] OCaml

Printf.printf "%09.3f\n" 7.125

[edit] Oz

It is possible to set the precision used for float printing (where "precision" means the total number of digits used).

It doesn't seem to be possible to use leading zeros for printing, so we implement this manually:

declare
fun {PrintFloat X Prec}
{Property.put 'print.floatPrecision' Prec}
S = {Float.toString X}
in
{Append
for I in 1..Prec-{Length S}+1 collect:C do {C &0} end
S}
end
in
{System.showInfo {PrintFloat 7.125 8}}

[edit] Perl

Works with: Perl version 5.x

printf " %09.3f\n", 7.125;

[edit] PHP

echo str_pad(7.125, 9, '0', STR_PAD_LEFT);

or

printf("%09.3f\n", 7.125);

[edit] PicoLisp

(pad 9 (format 7125 3))
(pad 9 (format 7125 3 ",")) # European format

[edit] PL/I

 
put edit (X) (p'999999.V999'); /* Western format. */
 
put edit (X) (p'999999,V999'); /* In European format. */
 
 

[edit] Pop11

The task is underspecified, so we present a few alternatives.

;;; field of length 12, 3 digits after decimal place
format_print('~12,3,0,`*,`0F', [1299.19]);
;;; prints "00001299.190"
format_print('~12,3,0,`*,`0F', [100000000000000000]);
;;; Since the number does not fit into the field prints "************"
;;; that is stars instead of the number
format_print('~12,3,0,`*,`0F', [-1299.19]);
;;; prints "000-1299.190"
;;; that is _leading zeros_ before sign
 
format_print('~3,1,12,`0:$', [1299.19]);
;;; prints "00001299.190"
format_print('~3,1,12,`0:$', [-1299.19]);
;;; prints "-0001299.190"
;;; that is sign before leading zeros
format_print('~3,1,12,`0:$', [100000000000000000]);
;;; prints "100000000000000000.000"
;;; that is uses more space if the number does not fit into
;;; fixed width

[edit] PowerShell

Using the -f formatting operator and a custom format string:

'{0:00000.000}' -f 7.125

or by invoking ToString on the number:

7.125.ToString('00000.000')

[edit] PureBasic

Using RSet() to pad 7.125 with 3 decimals converted to a string, to 8 char length.

RSet(StrF(7.125,3),8,"0")    ; Will be 0007.125

[edit] Python

Works with: Python version 2.5 Python has 3 different floating point formatting methods: "%e","%f" & "%g". The "%g" format is a beautified hybrid of "%e" and "%f". There is no way of specifying how many digits appear in the exponent when printed with a format.

from math import pi, exp
r = exp(pi)-pi
print r
print "e=%e f=%f g=%g G=%G s=%s r=%r!"%(r,r,r,r,r,r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(-r,-r,-r)
print "e=%9.4e f=%9.4f g=%9.4g!"%(r,r,r)
print "e=%-9.4e f=%-9.4f g=%-9.4g!"%(r,r,r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(-r,-r,-r)
print "e=%09.4e f=%09.4f g=%09.4g!"%(r,r,r)
print "e=%-09.4e f=%-09.4f g=%-09.4g!"%(r,r,r)
19.9990999792
e=1.999910e+01 f=19.999100 g=19.9991 G=19.9991 s=19.9990999792 r=19.999099979189474!
e=-1.9999e+01 f= -19.9991 g=      -20!
e=1.9999e+01 f=  19.9991 g=       20!
e=1.9999e+01 f=19.9991   g=20       !
e=-1.9999e+01 f=-019.9991 g=-00000020!
e=1.9999e+01 f=0019.9991 g=000000020!
e=1.9999e+01 f=19.9991   g=20       !

Works with: Python version 3

from math import pi, exp
r = exp(pi)-pi
print(r)
print("e={0:e} f={0:f} g={0:g} G={0:G} s={0!s} r={0!r}!".format(r))
print("e={0:9.4e} f={0:9.4f} g={0:9.4g}!".format(-r))
print("e={0:9.4e} f={0:9.4f} g={0:9.4g}!".format(r))
print("e={0:-9.4e} f={0:-9.4f} g={0:-9.4g}!".format(r))
print("e={0:09.4e} f={0:09.4f} g={0:09.4g}!".format(-r))
print("e={0:09.4e} f={0:09.4f} g={0:09.4g}!".format(r))
print("e={0:-09.4e} f={0:-09.4f} g={0:-09.4g}!".format(r))
19.9990999792
e=1.999910e+01 f=19.999100 g=19.9991 G=19.9991 s=19.9990999792 r=19.999099979189474!
e=-1.9999e+01 f= -19.9991 g=      -20!
e=1.9999e+01 f=  19.9991 g=       20!
e=1.9999e+01 f=19.9991   g=20       !
e=-1.9999e+01 f=-019.9991 g=-00000020!
e=1.9999e+01 f=0019.9991 g=000000020!
e=1.9999e+01 f=19.9991   g=20       !

[edit] R

formatC provides C-style string formatting.

formatC(x, width=9, flag="0")
# "00007.125"

Other string formatting functions include

format, prettynum

[edit] REBOL

rebol [
Title: "Formatted Numeric Output"
Author: oofoe
Date: 2009-12-22
URL: http://rosettacode.org/wiki/Formatted_Numeric_Output
]

 
; REBOL has no built-in facilities for printing pictured
; output. However, it's not too hard to cook something up using the
; string manipulation facilities.
 
zeropad: func [
"Pad number with zeros or spaces. Works on entire number."
pad "Number of characters to pad to."
n "Number to pad."
/space "Pad with spaces instead."
/local nn c s
][
n: to-string n c: " " s: ""
 
if not space [
c: "0"
if #"-" = n/1 [pad: pad - 1 n: copy skip n 1 s: "-"]
]
 
insert/dup n c (pad - length? n)
insert n s
n
]
 
; These tests replicate the C example output.
 
print [zeropad/space 9 negate 7.125]
print [zeropad/space 9 7.125]
print 7.125
print [zeropad 9 negate 7.125]
print [zeropad 9 7.125]
print 7.125

Output:

   -7.125
    7.125
7.125
-0007.125
00007.125
7.125

[edit] Raven

7.125 "%09.3f" print
 
00007.125

[edit] Ruby

printf " %09.3f\n", 7.125

[edit] Sather

The Fill options should fill with any character, but it is still (!) not implemented; according to ICSI Sather library documentation (GNU Sather library documentation is missing) works only for string, bools and characters, but a test has revealed it does not work in either way (yet) (GNU Sather v1.2.3).

class MAIN is
main is
#OUT + #FMT("<F0 #####.###>", 7.1257) + "\n";
#OUT + #FMT("<F0 #####.###>", 7.1254) + "\n";
end;
end;

Luckly the C-like formats are supported too:

    #OUT + #FMT("%09.3f", 7.125) + "\n";

[edit] SQL

Works with: MS SQL version 2005

DECLARE @n INT
SELECT @n=123
SELECT SUBSTRING(CONVERT(CHAR(5), 10000+@n),2,4) AS FourDigits
 
SET @n=5
print "TwoDigits: " + SUBSTRING(CONVERT(CHAR(3), 100+@n),2,2)
--Output: 05

[edit] Standard ML

print (StringCvt.padLeft #"0" 9 (Real.fmt (StringCvt.FIX (SOME 3)) 7.125) ^ "\n")

[edit] Suneido

Print(7.125.Pad(9))

Output:

00007.125

[edit] Tcl

set number 7.342
format "%08.3f" $number

Use with puts if output is desired to go to a channel.

[edit] TI-89 BASIC

This example is in need of improvement:
It does not handle negative numbers.
right("00000" & format(7.12511, "f3"), 9)

[edit] Toka

needs values
value n
123 to n
 
2 import printf
" %08d" n printf

[edit] Ursala

The library function printf calls the host system's C library function by that name and can cope with any of the same numeric formats.

#import flo
 
x = 7.125
 
#show+
 
t = <printf/'%09.3f' x>

output:

00007.125

[edit] Vedit macro language

Vedit only supports integers, but fixed point calculations can be used for decimal values.
The following example uses 3 decimal places (value scaled by 1000). The output is inserted at current edit position.

#1 = 7125
Num_Ins(#1, FILL+COUNT, 9) Char(-3) Ins_Char('.')

Output:

 00007.125

[edit] XSLT

<xsl:value-of select="format-number(7.125, '00000000.#############')" />
Personal tools