PHP's bcround in TypeScript

How to use

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

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

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
1bcround(1, 2)'1.00'

Dependencies

This function uses the following Locutus functions:

  • _bc (php/_helpers)

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

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

export function bcround(val: number, precision: number): string {
// discuss at: https://locutus.io/php/bcround/
// original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
// example 1: bcround(1, 2)
// returns 1: '1.00'

const libbcmath = _bc()

let temp
let result
let digit
let rightOperand

// create number
temp = libbcmath.bc_init_num()
temp = libbcmath.php_str2num(val.toString())

// check if any rounding needs
if (precision >= temp.n_scale) {
// nothing to round, just add the zeros.
while (temp.n_scale < precision) {
temp.n_value[temp.n_len + temp.n_scale] = 0
temp.n_scale++
}
return temp.toString()
}

// get the digit we are checking (1 after the precision)
// loop through digits after the precision marker
digit = temp.n_value[temp.n_len + precision] ?? 0

rightOperand = libbcmath.bc_init_num()
rightOperand = libbcmath.bc_new_num(1, precision)

if (digit >= 5) {
// round away from zero by adding 1 (or -1) at the "precision"..
// ie 1.44999 @ 3dp = (1.44999 + 0.001).toString().substr(0,5)
rightOperand.n_value[rightOperand.n_len + rightOperand.n_scale - 1] = 1
if (temp.n_sign === libbcmath.MINUS) {
// round down
rightOperand.n_sign = libbcmath.MINUS
}
result = libbcmath.bc_add(temp, rightOperand, precision)
} else {
// leave-as-is.. just truncate it.
result = temp
}

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

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