or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

base-converter.mdcurrency-conversion.mdindex.mdlanguage-support.mdnumber-conversion.mdutility-functions.md

currency-conversion.mddocs/

0

# Currency Conversion

1

2

Specialized functionality for converting numbers to properly localized currency representations. The num2words library provides comprehensive currency support with language-specific formatting, pluralization rules, and cultural conventions.

3

4

## Capabilities

5

6

### Currency Conversion Function

7

8

Convert numeric values to currency word representations with extensive customization options.

9

10

```python { .api }

11

def to_currency(val, currency='EUR', cents=True, separator=',', adjective=False):

12

"""

13

Convert number to currency word representation.

14

15

Parameters:

16

- val: int/float/Decimal - Currency value to convert

17

- currency: str - Currency code (default: 'EUR')

18

- cents: bool - Use verbose cents representation (default: True)

19

- separator: str - Separator between currency and cents (default: ',')

20

- adjective: bool - Include currency adjective prefix (default: False)

21

22

Returns:

23

str - Formatted currency string with proper localization

24

25

Raises:

26

NotImplementedError - If currency not supported for language

27

"""

28

```

29

30

**Usage Examples:**

31

32

```python

33

from num2words import num2words

34

35

# Basic currency conversion (EUR default)

36

result = num2words(42.50, to='currency')

37

# "forty-two euros, fifty cents"

38

39

# Different currencies

40

result = num2words(42.50, to='currency', currency='USD')

41

# "forty-two dollars, fifty cents"

42

43

result = num2words(42.50, to='currency', currency='GBP')

44

# "forty-two pounds, fifty pence"

45

46

# Different languages

47

result = num2words(42.50, to='currency', lang='fr')

48

# "quarante-deux euros, cinquante centimes"

49

50

result = num2words(42.50, to='currency', lang='es')

51

# "cuarenta y dos euros, cincuenta céntimos"

52

```

53

54

### Currency Formatting Options

55

56

Control various aspects of currency formatting.

57

58

**Cents Representation:**

59

60

```python

61

# Verbose cents (default)

62

num2words(42.50, to='currency', cents=True)

63

# "forty-two euros, fifty cents"

64

65

# Numeric cents

66

num2words(42.50, to='currency', cents=False)

67

# "forty-two euros, 50"

68

69

# Zero cents handling

70

num2words(42.00, to='currency')

71

# "forty-two euros" (no cents when zero)

72

73

num2words(42.00, to='currency', cents=False)

74

# "forty-two euros, 00" (explicit numeric format)

75

```

76

77

**Separator Customization:**

78

79

```python

80

# Default comma separator

81

num2words(42.50, to='currency')

82

# "forty-two euros, fifty cents"

83

84

# Custom separators

85

num2words(42.50, to='currency', separator=' and ')

86

# "forty-two euros and fifty cents"

87

88

num2words(42.50, to='currency', separator=' with ')

89

# "forty-two euros with fifty cents"

90

91

num2words(42.50, to='currency', separator='/')

92

# "forty-two euros/fifty cents"

93

```

94

95

**Currency Adjectives:**

96

97

```python

98

# Standard currency names

99

num2words(42.50, to='currency', currency='EUR')

100

# "forty-two euros, fifty cents"

101

102

# With adjective prefix (when supported)

103

num2words(42.50, to='currency', currency='EUR', adjective=True)

104

# "forty-two European euros, fifty European cents" (if supported)

105

```

106

107

### Currency Parsing and Processing

108

109

Internal functions for handling currency value parsing.

110

111

```python { .api }

112

def parse_currency_parts(value, is_int_with_cents=True):

113

"""

114

Parse currency value into integer and cents components.

115

116

Parameters:

117

- value: int/float/Decimal - Currency value

118

- is_int_with_cents: bool - Treat integers as cents (default: True)

119

120

Returns:

121

tuple - (integer_part, cents_part, is_negative)

122

123

Raises:

124

ValueError - For invalid currency values

125

"""

126

```

127

128

**Usage Examples:**

129

130

```python

131

from num2words.currency import parse_currency_parts

132

133

# Float input

134

integer, cents, negative = parse_currency_parts(42.50)

135

# (42, 50, False)

136

137

# Integer input (treated as cents by default)

138

integer, cents, negative = parse_currency_parts(4250)

139

# (42, 50, False)

140

141

# Integer input (treated as whole units)

142

integer, cents, negative = parse_currency_parts(42, is_int_with_cents=False)

143

# (42, 0, False)

144

145

# Negative values

146

integer, cents, negative = parse_currency_parts(-42.50)

147

# (42, 50, True)

148

149

# String input

150

integer, cents, negative = parse_currency_parts("42.50")

151

# (42, 50, False)

152

```

153

154

### Currency Internal Processing Methods

155

156

Internal methods used by the currency conversion system for formatting currency components.

157

158

```python { .api }

159

def _money_verbose(self, number, currency):

160

"""

161

Convert currency major unit to verbose word representation.

162

163

Internal method used by to_currency() for the main currency amount.

164

165

Parameters:

166

- number: int - Major currency unit amount

167

- currency: str - Currency code

168

169

Returns:

170

str - Verbose word representation of major currency unit

171

"""

172

173

def _cents_verbose(self, number, currency):

174

"""

175

Convert currency minor unit to verbose word representation.

176

177

Internal method used by to_currency() for cents/minor units when cents=True.

178

179

Parameters:

180

- number: int - Minor currency unit amount (cents)

181

- currency: str - Currency code

182

183

Returns:

184

str - Verbose word representation of minor currency unit

185

"""

186

187

def _cents_terse(self, number, currency):

188

"""

189

Convert currency minor unit to terse numeric representation.

190

191

Internal method used by to_currency() for cents/minor units when cents=False.

192

193

Parameters:

194

- number: int - Minor currency unit amount (cents)

195

- currency: str - Currency code

196

197

Returns:

198

str - Terse numeric representation (e.g., "05", "50")

199

"""

200

```

201

202

**Usage Examples:**

203

204

```python

205

from num2words import CONVERTER_CLASSES

206

207

# These are internal methods used by to_currency()

208

en_converter = CONVERTER_CLASSES['en']

209

210

# Internal currency processing

211

money_part = en_converter._money_verbose(42, 'EUR') # "forty-two"

212

cents_part = en_converter._cents_verbose(50, 'EUR') # "fifty"

213

cents_terse = en_converter._cents_terse(50, 'EUR') # "50"

214

215

# These methods are combined by to_currency() for final output

216

# "forty-two euros, fifty cents" (verbose)

217

# "forty-two euros, 50" (terse)

218

```

219

220

### Currency Forms and Localization

221

222

Each language defines its own currency forms and pluralization rules.

223

224

```python { .api }

225

# Currency forms structure (language-specific)

226

CURRENCY_FORMS = {

227

'EUR': (('euro', 'euros'), ('cent', 'cents')),

228

'USD': (('dollar', 'dollars'), ('cent', 'cents')),

229

'GBP': (('pound', 'pounds'), ('penny', 'pence')),

230

'JPY': (('yen', 'yen'), ('sen', 'sen')),

231

# ... more currencies per language

232

}

233

234

# Currency adjectives (when supported)

235

CURRENCY_ADJECTIVES = {

236

'EUR': 'European',

237

'USD': 'American',

238

'GBP': 'British',

239

# ... more adjectives per language

240

}

241

```

242

243

**Language-Specific Currency Examples:**

244

245

```python

246

# English currency forms

247

num2words(42.50, to='currency', lang='en', currency='USD')

248

# "forty-two dollars, fifty cents"

249

250

num2words(42.50, to='currency', lang='en', currency='GBP')

251

# "forty-two pounds, fifty pence"

252

253

# French currency forms

254

num2words(42.50, to='currency', lang='fr', currency='EUR')

255

# "quarante-deux euros, cinquante centimes"

256

257

# Spanish currency forms

258

num2words(42.50, to='currency', lang='es', currency='EUR')

259

# "cuarenta y dos euros, cincuenta céntimos"

260

261

# German currency forms

262

num2words(42.50, to='currency', lang='de', currency='EUR')

263

# "zweiundvierzig Euro, fünfzig Cent"

264

```

265

266

### Pluralization Rules

267

268

Currency conversion uses language-specific pluralization rules.

269

270

```python { .api }

271

def pluralize(self, n, forms):

272

"""

273

Apply language-specific pluralization to currency forms.

274

275

Parameters:

276

- n: int - Number for pluralization decision

277

- forms: tuple - (singular, plural) forms

278

279

Returns:

280

str - Correctly pluralized form

281

"""

282

```

283

284

**Pluralization Examples:**

285

286

```python

287

# English pluralization

288

num2words(1.00, to='currency', currency='USD')

289

# "one dollar" (singular)

290

291

num2words(2.00, to='currency', currency='USD')

292

# "two dollars" (plural)

293

294

num2words(1.01, to='currency', currency='USD')

295

# "one dollar, one cent" (singular forms)

296

297

num2words(1.02, to='currency', currency='USD')

298

# "one dollar, two cents" (mixed singular/plural)

299

300

# Special cases in different languages

301

num2words(1.00, to='currency', lang='fr', currency='EUR')

302

# "un euro" (French singular)

303

304

num2words(2.00, to='currency', lang='fr', currency='EUR')

305

# "deux euros" (French plural)

306

```

307

308

### Supported Currencies by Language

309

310

Different languages support different sets of currencies.

311

312

**Common Currency Codes:**

313

314

```python

315

# Major world currencies

316

'EUR' # Euro

317

'USD' # US Dollar

318

'GBP' # British Pound

319

'JPY' # Japanese Yen

320

'CAD' # Canadian Dollar

321

'AUD' # Australian Dollar

322

'CHF' # Swiss Franc

323

'CNY' # Chinese Yuan

324

'SEK' # Swedish Krona

325

'NOK' # Norwegian Krone

326

'DKK' # Danish Krone

327

'PLN' # Polish Zloty

328

'CZK' # Czech Koruna

329

'HUF' # Hungarian Forint

330

'RUB' # Russian Ruble

331

'INR' # Indian Rupee

332

'BRL' # Brazilian Real

333

'MXN' # Mexican Peso

334

'ZAR' # South African Rand

335

'KRW' # South Korean Won

336

```

337

338

**Testing Currency Support:**

339

340

```python

341

def test_currency_support(lang, currency):

342

"""Test if a currency is supported for a language."""

343

try:

344

result = num2words(42.50, to='currency', lang=lang, currency=currency)

345

return True, result

346

except NotImplementedError as e:

347

return False, str(e)

348

349

# Test various combinations

350

support, result = test_currency_support('en', 'USD')

351

support, result = test_currency_support('fr', 'EUR')

352

support, result = test_currency_support('ja', 'JPY')

353

```

354

355

### Currency Prefix Utilities

356

357

Helper functions for handling currency adjectives and prefixes.

358

359

```python { .api }

360

def prefix_currency(prefix, base):

361

"""

362

Add prefix to currency forms.

363

364

Parameters:

365

- prefix: str - Prefix to add (e.g., "European")

366

- base: tuple - Base currency forms (singular, plural)

367

368

Returns:

369

tuple - Prefixed currency forms

370

"""

371

```

372

373

**Usage Examples:**

374

375

```python

376

from num2words.currency import prefix_currency

377

378

# Add adjective prefix

379

base_forms = ('euro', 'euros')

380

prefixed = prefix_currency('European', base_forms)

381

# ('European euro', 'European euros')

382

383

# Use in currency conversion

384

num2words(42.50, to='currency', adjective=True)

385

# Uses prefixed forms when adjectives are defined

386

```

387

388

### Integer vs. Float Currency Handling

389

390

Different handling for integer and float currency inputs.

391

392

```python

393

# Integer inputs (interpreted as cents by default)

394

num2words(4250, to='currency') # 4250 cents = 42.50 currency units

395

# "forty-two euros, fifty cents"

396

397

# Float inputs (direct value interpretation)

398

num2words(42.50, to='currency')

399

# "forty-two euros, fifty cents"

400

401

# Force integer interpretation as whole units

402

from num2words.currency import parse_currency_parts

403

integer, cents, negative = parse_currency_parts(42, is_int_with_cents=False)

404

# Then use with currency conversion

405

406

# Decimal precision handling

407

num2words(42.567, to='currency') # Rounded to 2 decimal places

408

# "forty-two euros, fifty-seven cents"

409

```

410

411

### Negative Currency Values

412

413

Handling of negative currency amounts.

414

415

```python

416

# Negative amounts

417

num2words(-42.50, to='currency')

418

# "minus forty-two euros, fifty cents"

419

420

num2words(-42.50, to='currency', lang='fr')

421

# French negative prefix with currency

422

423

# Zero and negative cents

424

num2words(-0.50, to='currency')

425

# "minus fifty cents"

426

```

427

428

### Error Handling

429

430

Currency conversion provides specific error handling for various scenarios.

431

432

```python

433

# Unsupported currency for language

434

try:

435

num2words(42.50, to='currency', lang='en', currency='UNSUPPORTED')

436

except NotImplementedError as e:

437

print(f"Currency not supported: {e}")

438

439

# Invalid currency values

440

try:

441

num2words("invalid", to='currency')

442

except ValueError as e:

443

print(f"Invalid currency value: {e}")

444

445

# Check currency support before use

446

def safe_currency_convert(value, lang, currency):

447

try:

448

return num2words(value, to='currency', lang=lang, currency=currency)

449

except NotImplementedError:

450

# Fallback to default currency

451

return num2words(value, to='currency', lang=lang, currency='EUR')

452

```

453

454

### Advanced Currency Formatting

455

456

Custom formatting options for specific use cases.

457

458

```python

459

# Long format with explicit separators

460

num2words(1234.56, to='currency', separator=' and ')

461

# "one thousand, two hundred and thirty-four euros and fifty-six cents"

462

463

# Terse format without verbose cents

464

num2words(1234.56, to='currency', cents=False)

465

# "one thousand, two hundred and thirty-four euros, 56"

466

467

# Cultural variations by language

468

num2words(1234.56, to='currency', lang='de') # German formatting

469

num2words(1234.56, to='currency', lang='ja') # Japanese formatting (if supported)

470

num2words(1234.56, to='currency', lang='ar') # Arabic formatting (if supported)

471

```