Taskintro
Print formatted output
Also called printf, formatted print, print a table, format a line, String.format, fmt.Printf, println!, Console.WriteLine, std::print, f-string, column alignment, fixed width output, print with padding.
Print a line of a table with a format: a name on the left in 10 columns, a count on the right in 5 and a price with 2 decimals in 8, with printf, format, println! and f-strings.
- Evidence
- Code in 10 languages
Task
Print values in fixed columns, so that the lines of a table line up. The Rosetta Code task asks for one case of this: "Express a number in decimal as a fixed-length string with leading zeros"1. This task does more: it formats a line with three columns of three types.
The function format_row(name, qty, price) returns one line:
name, a string, on the left of a column of 10 characters;- a bar
|; qty, an integer, on the right of a column of 5 characters;- a bar
|; price, a float, rounded to 2 decimals, on the right of a column of 8 characters.
In C notation, the format is "%-10s|%5d|%8.2f". For example, format_row("apple", 3, 1.5) is "apple | 3| 1.50". A program prints the lines one after the other:
apple | 3| 1.50
widget | 12| 19.99
laptop | 1| 1234.50
A width is a minimum, not a maximum. A value that is wider than its column is not cut, so the line becomes longer. In C, the width "specifies minimum field width. The result is padded with space characters (by default), if required, on the left when right-justified, or on the right if left-justified"2.
The function returns the line, and the caller prints it. Then the tests can check the text, and the same function can write to a file or a socket.
Solutions
Each tier 1 language has a format function in its standard library, except JavaScript.
| Language | Function | Format |
|---|---|---|
| Python | f-string | f"{name:<10}|{qty:5d}|{price:8.2f}" |
| JavaScript, TypeScript | padEnd, padStart, toFixed |
no format string |
| Java | String.format |
"%-10s|%5d|%8.2f" |
| C# | string.Format |
"{0,-10}|{1,5}|{2,8:F2}" |
| Go | fmt.Sprintf |
"%-10s|%5d|%8.2f" |
| Rust | format! |
"{name:<10}|{qty:5}|{price:8.2}" |
| C | snprintf |
"%-10s|%5lld|%8.2f" |
| C++ | std::format |
"{:<10}|{:5}|{:8.2f}" |
| Bash | printf -v |
'%-10s|%5d|%8.2f' |
- Python. An f-string with a format specifier after each colon.
<forces the field to be left-aligned: "'<' Forces the field to be left-aligned within the available space (this is the default for most objects)"3. To print, callprint(format_row(...)). - JavaScript. JavaScript has no format strings.
toFixed(2)gives the 2 decimals, andpadStartandpadEndgive the width.padStart"pads this string with a given string (repeated and/or truncated, if needed) so that the resulting string has a given length"4. The functiontoFixedreturns the number "without using exponential notation and with exactly digits digits after the decimal point"5. - TypeScript. The same code as JavaScript, with types.
- Java.
String.formatwith the specifiers of C. The width "is a positive decimal integer indicating the minimum number of characters to be written to the output"6. The solution passesLocale.ROOT, so the decimal point is always.. - C#.
string.Formatwith format items. In{0,-10}, the number after the comma is the width, and a minus sign puts the value on the left. "If the value of width is less than the length of the formatted string, width is ignored, and the length of the formatted string is used as the field width"7. The solution passesCultureInfo.InvariantCulture. - Go.
fmt.Sprintf"formats according to a format specifier and returns the resulting string"8.fmt.Printfprints the same text. - Rust. The macro
format!with named arguments.println!prints the same text: it is the same asprint!, "but appends a newline"9. - C.
snprintfwrites into a buffer of a given size and returns the length of the full text. The solution returns that length, so the caller can see if the buffer was too small. - C++.
std::formatreturns astd::string. It "Format args according to the format string fmt, and return the result as a string"10.std::printprints the same text. - Bash. The builtin
printf -v linewrites the text into the variableline. Without-v,printfprints the text.
The Python solution and a loop that prints a table:
def format_row(name, qty, price):
return f"{name:<10}|{qty:5d}|{price:8.2f}"
rows = [("apple", 3, 1.5), ("widget", 12, 19.99), ("laptop", 1, 1234.5)]
print(f"{'item':<10}|{'qty':>5}|{'price':>8}")
print("-" * 10 + "+" + "-" * 5 + "+" + "-" * 8)
for row in rows:
print(format_row(*row))
item | qty| price
----------+-----+--------
apple | 3| 1.50
widget | 12| 19.99
laptop | 1| 1234.50
The same line in Go, with Printf:
package main
import "fmt"
func main() {
fmt.Printf("%-10s|%5d|%8.2f\n", "apple", 3, 1.5)
fmt.Printf("%-10s|%5d|%8.2f\n", "watermelonade", 123456, 123456.75)
}
apple | 3| 1.50
watermelonade|123456|123456.75
The second line shows that a long value moves the columns after it.
Edge cases
- Empty name. The name column is 10 spaces.
- A value of the exact width.
abcdefghij,99999and99999.99fill their columns with no spaces. - A value wider than its column. The value is not cut, and the line is longer. A table that must stay aligned needs the widest value first: see the task
align-columns-of-text. - Negative numbers. The minus sign counts in the width:
-3.50takes 5 of the 8 characters. - Rounding.
0.006gives0.01, and2.344gives2.34. The contract has no value that is halfway between two results, because the languages do not round those values in the same way. - Spaces and format characters in the name. A name such as
100% {x}is a value, not a format string, so the%and the braces are copied as they are.
Pitfalls
- The locale of the computer. In Java and C#, a format call with no locale uses the locale of the user. On a computer with a German locale,
String.format("%.2f", 1.5)gives1,50. PassLocale.ROOTorCultureInfo.InvariantCulturefor text that a program reads. See Locale-aware formatting. - The wrong type for a specifier. In C,
%dwith along longis undefined behavior. Use%lld. In Go, a wrong type gives a text such as%!d(string=3)in the output. - The value as the format string. Never pass a value as the format:
printf(name)treats each%in the name as a specifier. Writeprintf("%s", name). - A width cuts nothing. A long value moves the next columns:
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
int main(void) {
printf("%-5s|%3d|\n", "pen", 7);
printf("%-5s|%3d|\n", "notebook", 12345);
return 0;
}
pen | 7|
notebook|12345|
To cut a string, give a precision: %-5.5s. Do not cut numbers, because a cut number is a wrong number.
- Wide characters. A width counts bytes in C and Bash, UTF-16 units in Java, C# and JavaScript, and code points in Python and Rust. A name with accents or Chinese characters can make a column too wide or too narrow. The contract uses ASCII names.
toFixedand large numbers. In JavaScript,toFixedgives exponential notation for numbers of 1e21 or more5. The contract keeps the price below 1e9.
Related tasks
- Interpolate values into a string: build a string with values and expressions inside.
- Format specifiers: the codes of the format strings, in each family.
- Locale-aware formatting: numbers with the symbols of a language and region.
- String interpolation: values inside string literals.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/print-formatted-output/.
def format_row(name: str, qty: int, price: float) -> str:
"""Return one line of a table: name in 10 columns on the left, qty in 5
on the right and price with 2 decimals in 8 on the right.
A width is a minimum, so a long value is not cut.
"""
return f"{name:<10}|{qty:5d}|{price:8.2f}"
if __name__ == "__main__":
for row in [("apple", 3, 1.5), ("widget", 12, 19.99), ("laptop", 1, 1234.5)]:
print(format_row(*row))
test_row.py 27 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/print-formatted-output/.
import pytest
from row import format_row
CASES = [
("apple", "apple", 3, 1.5, "apple | 3| 1.50"),
("widget", "widget", 12, 19.99, "widget | 12| 19.99"),
("laptop", "laptop", 1, 1234.5, "laptop | 1| 1234.50"),
("empty-name", "", 0, 0.0, " | 0| 0.00"),
("exact-widths", "abcdefghij", 99999, 99999.99, "abcdefghij|99999|99999.99"),
("long-name", "watermelonade", 5, 2.0, "watermelonade| 5| 2.00"),
("wide-quantity", "pen", 123456, 0.5, "pen |123456| 0.50"),
("wide-price", "car", 1, 123456.75, "car | 1|123456.75"),
("negative-values", "refund", -2, -3.5, "refund | -2| -3.50"),
("rounds-up", "nail", 1000, 0.006, "nail | 1000| 0.01"),
("rounds-down", "bolt", 7, 2.344, "bolt | 7| 2.34"),
("name-with-spaces", "blue pen", 4, 0.99, "blue pen | 4| 0.99"),
("name-with-percent", "100% {x}", 1, 1.0, "100% {x} | 1| 1.00"),
]
@pytest.mark.parametrize(("name", "item", "qty", "price", "want"), CASES, ids=[c[0] for c in CASES])
def test_format_row(name, item, qty, price, want):
assert format_row(item, qty, price) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
#ifndef ROW_HPP
#define ROW_HPP
#include <cstdint>
#include <format>
#include <string>
#include <string_view>
// Returns name in 10 columns on the left, qty in 5 on the right and price
// with 2 decimals in 8 on the right. A width is a minimum, so a long value is
// not cut.
inline std::string format_row(std::string_view name, std::int64_t qty, double price) {
return std::format("{:<10}|{:5}|{:8.2f}", name, qty, price);
}
#endif
test_row.cpp 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
#include <cstdint>
#include <cstdio>
#include "row.hpp"
namespace {
struct test_case {
const char* name;
const char* item;
std::int64_t qty;
double price;
const char* want;
};
const test_case cases[] = {
{"apple", "apple", 3, 1.5, "apple | 3| 1.50"},
{"widget", "widget", 12, 19.99, "widget | 12| 19.99"},
{"laptop", "laptop", 1, 1234.5, "laptop | 1| 1234.50"},
{"empty-name", "", 0, 0.0, " | 0| 0.00"},
{"exact-widths", "abcdefghij", 99999, 99999.99, "abcdefghij|99999|99999.99"},
{"long-name", "watermelonade", 5, 2.0, "watermelonade| 5| 2.00"},
{"wide-quantity", "pen", 123456, 0.5, "pen |123456| 0.50"},
{"wide-price", "car", 1, 123456.75, "car | 1|123456.75"},
{"negative-values", "refund", -2, -3.5, "refund | -2| -3.50"},
{"rounds-up", "nail", 1000, 0.006, "nail | 1000| 0.01"},
{"rounds-down", "bolt", 7, 2.344, "bolt | 7| 2.34"},
{"name-with-spaces", "blue pen", 4, 0.99, "blue pen | 4| 0.99"},
{"name-with-percent", "100% {x}", 1, 1.0, "100% {x} | 1| 1.00"},
};
} // namespace
int main() {
int failures = 0;
for (const auto& c : cases) {
const std::string got = format_row(c.item, c.qty, c.price);
if (got != c.want) {
std::printf("FAIL %s: got \"%s\"\n", c.name, got.c_str());
++failures;
}
}
if (failures != 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
import java.util.Locale;
/** One line of a table with fixed columns. */
public final class Row {
private Row() {}
/**
* Returns name in 10 columns on the left, qty in 5 on the right and price
* with 2 decimals in 8 on the right. Locale.ROOT keeps the decimal point a
* dot on each computer. A width is a minimum, so a long value is not cut.
*/
public static String formatRow(String name, long qty, double price) {
return String.format(Locale.ROOT, "%-10s|%5d|%8.2f", name, qty, price);
}
public static void main(String[] args) {
System.out.println(formatRow("apple", 3, 1.5));
System.out.println(formatRow("widget", 12, 19.99));
}
}
RowTest.java 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class RowTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("apple", "apple", 3, 1.5, "apple | 3| 1.50"),
Arguments.of("widget", "widget", 12, 19.99, "widget | 12| 19.99"),
Arguments.of("laptop", "laptop", 1, 1234.5, "laptop | 1| 1234.50"),
Arguments.of("empty-name", "", 0, 0.0, " | 0| 0.00"),
Arguments.of("exact-widths", "abcdefghij", 99999, 99999.99, "abcdefghij|99999|99999.99"),
Arguments.of("long-name", "watermelonade", 5, 2.0, "watermelonade| 5| 2.00"),
Arguments.of("wide-quantity", "pen", 123456, 0.5, "pen |123456| 0.50"),
Arguments.of("wide-price", "car", 1, 123456.75, "car | 1|123456.75"),
Arguments.of("negative-values", "refund", -2, -3.5, "refund | -2| -3.50"),
Arguments.of("rounds-up", "nail", 1000, 0.006, "nail | 1000| 0.01"),
Arguments.of("rounds-down", "bolt", 7, 2.344, "bolt | 7| 2.34"),
Arguments.of("name-with-spaces", "blue pen", 4, 0.99, "blue pen | 4| 0.99"),
Arguments.of("name-with-percent", "100% {x}", 1, 1.0, "100% {x} | 1| 1.00")
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void formatRow(String name, String item, long qty, double price, String want) {
assertEquals(want, Row.formatRow(item, qty, price));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
#include "row.h"
#include <stdio.h>
int format_row(char *out, size_t size, const char *name, long long qty, double price) {
return snprintf(out, size, "%-10s|%5lld|%8.2f", name, qty, price);
}
row.h 15 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
#ifndef ROW_H
#define ROW_H
#include <stddef.h>
// Writes one line of a table into out: name in 10 columns on the left, qty
// in 5 on the right and price with 2 decimals in 8 on the right. Returns the
// length of the full line, as snprintf does. If the result is size or more,
// the line was cut to fit the buffer.
int format_row(char *out, size_t size, const char *name, long long qty, double price);
#endif
test_row.c 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
#include "row.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct test_case {
const char *name;
const char *item;
long long qty;
double price;
const char *want;
};
static const struct test_case cases[] = {
{"apple", "apple", 3, 1.5, "apple | 3| 1.50"},
{"widget", "widget", 12, 19.99, "widget | 12| 19.99"},
{"laptop", "laptop", 1, 1234.5, "laptop | 1| 1234.50"},
{"empty-name", "", 0, 0.0, " | 0| 0.00"},
{"exact-widths", "abcdefghij", 99999, 99999.99, "abcdefghij|99999|99999.99"},
{"long-name", "watermelonade", 5, 2.0, "watermelonade| 5| 2.00"},
{"wide-quantity", "pen", 123456, 0.5, "pen |123456| 0.50"},
{"wide-price", "car", 1, 123456.75, "car | 1|123456.75"},
{"negative-values", "refund", -2, -3.5, "refund | -2| -3.50"},
{"rounds-up", "nail", 1000, 0.006, "nail | 1000| 0.01"},
{"rounds-down", "bolt", 7, 2.344, "bolt | 7| 2.34"},
{"name-with-spaces", "blue pen", 4, 0.99, "blue pen | 4| 0.99"},
{"name-with-percent", "100% {x}", 1, 1.0, "100% {x} | 1| 1.00"},
};
int main(void) {
int failures = 0;
char buf[64];
for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
const struct test_case *c = &cases[i];
int n = format_row(buf, sizeof buf, c->item, c->qty, c->price);
if (n != (int)strlen(c->want) || strcmp(buf, c->want) != 0) {
printf("FAIL %s: got \"%s\"\n", c->name, buf);
failures++;
}
}
char small[8];
if (format_row(small, sizeof small, "apple", 3, 1.5) != 25 || strcmp(small, "apple ") != 0) {
printf("FAIL small buffer\n");
failures++;
}
if (failures != 0) {
return EXIT_FAILURE;
}
printf("ok\n");
return EXIT_SUCCESS;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
using System.Globalization;
/// <summary>One line of a table with fixed columns.</summary>
public static class Row
{
/// <summary>
/// Returns name in 10 columns on the left, qty in 5 on the right and price
/// with 2 decimals in 8 on the right. The invariant culture keeps the
/// decimal point a dot. A width is a minimum, so a long value is not cut.
/// </summary>
public static string FormatRow(string name, long qty, double price) =>
string.Format(CultureInfo.InvariantCulture, "{0,-10}|{1,5}|{2,8:F2}", name, qty, price);
}
RowTests.cs 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
using Xunit;
public sealed class RowTests
{
public static TheoryData<string, string, long, double, string> Cases => new()
{
{ "apple", "apple", 3, 1.5, "apple | 3| 1.50" },
{ "widget", "widget", 12, 19.99, "widget | 12| 19.99" },
{ "laptop", "laptop", 1, 1234.5, "laptop | 1| 1234.50" },
{ "empty-name", "", 0, 0.0, " | 0| 0.00" },
{ "exact-widths", "abcdefghij", 99999, 99999.99, "abcdefghij|99999|99999.99" },
{ "long-name", "watermelonade", 5, 2.0, "watermelonade| 5| 2.00" },
{ "wide-quantity", "pen", 123456, 0.5, "pen |123456| 0.50" },
{ "wide-price", "car", 1, 123456.75, "car | 1|123456.75" },
{ "negative-values", "refund", -2, -3.5, "refund | -2| -3.50" },
{ "rounds-up", "nail", 1000, 0.006, "nail | 1000| 0.01" },
{ "rounds-down", "bolt", 7, 2.344, "bolt | 7| 2.34" },
{ "name-with-spaces", "blue pen", 4, 0.99, "blue pen | 4| 0.99" },
{ "name-with-percent", "100% {x}", 1, 1.0, "100% {x} | 1| 1.00" },
};
[Theory]
[MemberData(nameof(Cases))]
public void FormatRow(string name, string item, long qty, double price, string want)
{
Assert.NotNull(name);
Assert.Equal(want, Row.FormatRow(item, qty, price));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
/**
* Returns one line of a table: name in 10 columns on the left, qty in 5 on
* the right and price with 2 decimals in 8 on the right. A width is a
* minimum, so a long value is not cut.
*/
export function formatRow(name, qty, price) {
return `${name.padEnd(10)}|${String(qty).padStart(5)}|${price.toFixed(2).padStart(8)}`;
}
row.test.js 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { formatRow } from "./row.js";
const cases = [
["apple", "apple", 3, 1.5, "apple | 3| 1.50"],
["widget", "widget", 12, 19.99, "widget | 12| 19.99"],
["laptop", "laptop", 1, 1234.5, "laptop | 1| 1234.50"],
["empty-name", "", 0, 0, " | 0| 0.00"],
["exact-widths", "abcdefghij", 99999, 99999.99, "abcdefghij|99999|99999.99"],
["long-name", "watermelonade", 5, 2, "watermelonade| 5| 2.00"],
["wide-quantity", "pen", 123456, 0.5, "pen |123456| 0.50"],
["wide-price", "car", 1, 123456.75, "car | 1|123456.75"],
["negative-values", "refund", -2, -3.5, "refund | -2| -3.50"],
["rounds-up", "nail", 1000, 0.006, "nail | 1000| 0.01"],
["rounds-down", "bolt", 7, 2.344, "bolt | 7| 2.34"],
["name-with-spaces", "blue pen", 4, 0.99, "blue pen | 4| 0.99"],
["name-with-percent", "100% {x}", 1, 1, "100% {x} | 1| 1.00"],
];
for (const [name, item, qty, price, want] of cases) {
test(name, () => {
assert.equal(formatRow(item, qty, price), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
/**
* Returns one line of a table: name in 10 columns on the left, qty in 5 on
* the right and price with 2 decimals in 8 on the right. A width is a
* minimum, so a long value is not cut.
*/
export function formatRow(name: string, qty: number, price: number): string {
return `${name.padEnd(10)}|${String(qty).padStart(5)}|${price.toFixed(2).padStart(8)}`;
}
row.test.ts 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { formatRow } from "./row.ts";
const cases: [string, string, number, number, string][] = [
["apple", "apple", 3, 1.5, "apple | 3| 1.50"],
["widget", "widget", 12, 19.99, "widget | 12| 19.99"],
["laptop", "laptop", 1, 1234.5, "laptop | 1| 1234.50"],
["empty-name", "", 0, 0, " | 0| 0.00"],
["exact-widths", "abcdefghij", 99999, 99999.99, "abcdefghij|99999|99999.99"],
["long-name", "watermelonade", 5, 2, "watermelonade| 5| 2.00"],
["wide-quantity", "pen", 123456, 0.5, "pen |123456| 0.50"],
["wide-price", "car", 1, 123456.75, "car | 1|123456.75"],
["negative-values", "refund", -2, -3.5, "refund | -2| -3.50"],
["rounds-up", "nail", 1000, 0.006, "nail | 1000| 0.01"],
["rounds-down", "bolt", 7, 2.344, "bolt | 7| 2.34"],
["name-with-spaces", "blue pen", 4, 0.99, "blue pen | 4| 0.99"],
["name-with-percent", "100% {x}", 1, 1, "100% {x} | 1| 1.00"],
];
for (const [name, item, qty, price, want] of cases) {
test(name, () => {
assert.equal(formatRow(item, qty, price), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
// Package row formats one line of a table with fixed columns.
package row
import "fmt"
// FormatRow returns name in 10 columns on the left, qty in 5 on the right
// and price with 2 decimals in 8 on the right. A width is a minimum, so a
// long value is not cut.
func FormatRow(name string, qty int64, price float64) string {
return fmt.Sprintf("%-10s|%5d|%8.2f", name, qty, price)
}
row_test.go 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
package row
import "testing"
var cases = []struct {
name string
item string
qty int64
price float64
want string
}{
{"apple", "apple", 3, 1.5, "apple | 3| 1.50"},
{"widget", "widget", 12, 19.99, "widget | 12| 19.99"},
{"laptop", "laptop", 1, 1234.5, "laptop | 1| 1234.50"},
{"empty-name", "", 0, 0.0, " | 0| 0.00"},
{"exact-widths", "abcdefghij", 99999, 99999.99, "abcdefghij|99999|99999.99"},
{"long-name", "watermelonade", 5, 2.0, "watermelonade| 5| 2.00"},
{"wide-quantity", "pen", 123456, 0.5, "pen |123456| 0.50"},
{"wide-price", "car", 1, 123456.75, "car | 1|123456.75"},
{"negative-values", "refund", -2, -3.5, "refund | -2| -3.50"},
{"rounds-up", "nail", 1000, 0.006, "nail | 1000| 0.01"},
{"rounds-down", "bolt", 7, 2.344, "bolt | 7| 2.34"},
{"name-with-spaces", "blue pen", 4, 0.99, "blue pen | 4| 0.99"},
{"name-with-percent", "100% {x}", 1, 1.0, "100% {x} | 1| 1.00"},
}
func TestFormatRow(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := FormatRow(c.item, c.qty, c.price); got != c.want {
t.Fatalf("FormatRow(%q, %d, %v) = %q, want %q", c.item, c.qty, c.price, got, c.want)
}
})
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
/// Returns name in 10 columns on the left, qty in 5 on the right and price
/// with 2 decimals in 8 on the right. A width is a minimum, so a long value
/// is not cut.
pub fn format_row(name: &str, qty: i64, price: f64) -> String {
format!("{name:<10}|{qty:5}|{price:8.2}")
}
tests/row_test.rs 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/print-formatted-output/.
use algo_print_formatted_output::format_row;
const CASES: &[(&str, &str, i64, f64, &str)] = &[
("apple", "apple", 3, 1.5, "apple | 3| 1.50"),
("widget", "widget", 12, 19.99, "widget | 12| 19.99"),
("laptop", "laptop", 1, 1234.5, "laptop | 1| 1234.50"),
("empty-name", "", 0, 0.0, " | 0| 0.00"),
("exact-widths", "abcdefghij", 99999, 99999.99, "abcdefghij|99999|99999.99"),
("long-name", "watermelonade", 5, 2.0, "watermelonade| 5| 2.00"),
("wide-quantity", "pen", 123456, 0.5, "pen |123456| 0.50"),
("wide-price", "car", 1, 123456.75, "car | 1|123456.75"),
("negative-values", "refund", -2, -3.5, "refund | -2| -3.50"),
("rounds-up", "nail", 1000, 0.006, "nail | 1000| 0.01"),
("rounds-down", "bolt", 7, 2.344, "bolt | 7| 2.34"),
("name-with-spaces", "blue pen", 4, 0.99, "blue pen | 4| 0.99"),
("name-with-percent", "100% {x}", 1, 1.0, "100% {x} | 1| 1.00"),
];
#[test]
fn cases() {
for &(name, item, qty, price, want) in CASES {
assert_eq!(format_row(item, qty, price), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/print-formatted-output/.
# format_row name qty price: print one line of a table, with name in 10
# columns on the left, qty in 5 on the right and price with 2 decimals in 8
# on the right. LC_NUMERIC=C keeps the decimal point a dot.
format_row() {
local line
LC_NUMERIC=C printf -v line '%-10s|%5d|%8.2f' "$1" "$2" "$3"
printf '%s\n' "$line"
}
test_row.bats 72 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/print-formatted-output/.
setup() {
source "$BATS_TEST_DIRNAME/row.sh"
}
@test "apple" {
run format_row 'apple' 3 1.5
[ "$output" = 'apple | 3| 1.50' ]
}
@test "widget" {
run format_row 'widget' 12 19.99
[ "$output" = 'widget | 12| 19.99' ]
}
@test "laptop" {
run format_row 'laptop' 1 1234.5
[ "$output" = 'laptop | 1| 1234.50' ]
}
@test "empty-name" {
run format_row '' 0 0
[ "$output" = ' | 0| 0.00' ]
}
@test "exact-widths" {
run format_row 'abcdefghij' 99999 99999.99
[ "$output" = 'abcdefghij|99999|99999.99' ]
}
@test "long-name" {
run format_row 'watermelonade' 5 2
[ "$output" = 'watermelonade| 5| 2.00' ]
}
@test "wide-quantity" {
run format_row 'pen' 123456 0.5
[ "$output" = 'pen |123456| 0.50' ]
}
@test "wide-price" {
run format_row 'car' 1 123456.75
[ "$output" = 'car | 1|123456.75' ]
}
@test "negative-values" {
run format_row 'refund' -2 -3.5
[ "$output" = 'refund | -2| -3.50' ]
}
@test "rounds-up" {
run format_row 'nail' 1000 0.006
[ "$output" = 'nail | 1000| 0.01' ]
}
@test "rounds-down" {
run format_row 'bolt' 7 2.344
[ "$output" = 'bolt | 7| 2.34' ]
}
@test "name-with-spaces" {
run format_row 'blue pen' 4 0.99
[ "$output" = 'blue pen | 4| 0.99' ]
}
@test "name-with-percent" {
run format_row '100% {x}' 1 1
[ "$output" = '100% {x} | 1| 1.00' ]
}
References
- Rosetta Code, Formatted numeric output (task text, from acmeism/RosettaCodeData), task text
- printf, fprintf, sprintf, snprintf, C reference, cppreference.com, Parameters; Return value
- string, Common string operations, Python documentation, Format Specification Mini-Language
- String.prototype.padStart(), MDN Web Docs, Description
- Number.prototype.toFixed(), MDN Web Docs, Description
- Class Formatter, Java SE 25 API, Format String Syntax
- Composite formatting, .NET documentation, Width component
- Package fmt, The Go Standard Library, Printing; Sprintf
- Module std::fmt, The Rust Standard Library, Width; Precision; Related macros
- std::format, C++ reference, cppreference.com, Description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 118D22 Edit this page History Report an error Markdown