Formatted numeric output: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 1: Line 1:
{{task}}
{{task}}
Express a number in decimal as a fixed-length string with leading zeros.
Express a number in decimal as a fixed-length string with leading zeros.

==[[Ada]]==
[[Category: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


==[[JavaScript]]==
==[[JavaScript]]==

Revision as of 05:32, 11 February 2007

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.

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 

JavaScript

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

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

Python

#tested in Python 2.4.1
n = 123
str = "%05d" % n  #5 places wide, leading zeros
print n, str
#output: 123 00123

SQL

--Tested MS SQL 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