PHP's printf in TypeScript

How to use

Install via yarn add locutus and import: import { printf } from 'locutus/php/strings/printf'.

Or with CommonJS: const { printf } = require('locutus/php/strings/printf')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1printf("%01.2f", 123.1)6

Dependencies

This function uses the following Locutus functions:

Here's what our current TypeScript equivalent to PHP's printf looks like.

import type { PhpRuntimeValue } from '../_helpers/_phpTypes.ts'
import { echo } from '../strings/echo.ts'
import { sprintf } from '../strings/sprintf.ts'

type PrintfValue = PhpRuntimeValue

export function printf(format: string, ...args: PrintfValue[]): number {
// discuss at: https://locutus.io/php/printf/
// original by: Ash Searle (https://hexmen.com/blog/)
// improved by: Michael White (https://getsprink.com)
// improved by: Brett Zamir (https://brett-zamir.me)
// example 1: printf("%01.2f", 123.1)
// returns 1: 6

const ret = sprintf(format, ...args)
if (ret === false) {
return 0
}
echo(ret)
return ret.length
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


« More PHP strings functions


Star