PHP's bcadd in TypeScript

How to use

Install via yarn add locutus and import: import { bcadd } from 'locutus/php/bc/bcadd'.

Or with CommonJS: const { bcadd } = require('locutus/php/bc/bcadd')

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
1bcadd('1', '2')'3'
2bcadd('-1', '5', 4)'4.0000'
3bcadd('1928372132132819737213', '8728932001983192837219398127471', 2)'8728932003911564969352217864684.00'

Dependencies

This function uses the following Locutus functions:

  • _bc (php/_helpers)

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

import { _bc as bc } from '../_helpers/_bc.ts'

export function bcadd(leftOperand: string, rightOperand: string, scale?: number): string {
// discuss at: https://locutus.io/php/bcadd/
// original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
// example 1: bcadd('1', '2')
// returns 1: '3'
// example 2: bcadd('-1', '5', 4)
// returns 2: '4.0000'
// example 3: bcadd('1928372132132819737213', '8728932001983192837219398127471', 2)
// returns 3: '8728932003911564969352217864684.00'

const libbcmath = bc()

let first
let second
let result

if (typeof scale === 'undefined') {
scale = libbcmath.scale
}
scale = scale < 0 ? 0 : scale

// create objects
first = libbcmath.bc_init_num()
second = libbcmath.bc_init_num()
result = libbcmath.bc_init_num()

first = libbcmath.php_str2num(leftOperand.toString())
second = libbcmath.php_str2num(rightOperand.toString())

result = libbcmath.bc_add(first, second, scale)

if (result.n_scale > scale) {
result.n_scale = scale
}

return result.toString()
}

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 bc functions


Star