PHP's bcround in JavaScript

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
module.exports = function bcround (val, precision) {
// discuss at: http://locutus.io/php/bcround/
// original by: lmeyrick (https://sourceforge.net/projects/bcmath-js/)
// example 1: bcround(1, 2)
// returns 1: '1.00'

var _bc = require('../_helpers/_bc')
var libbcmath = _bc()

var temp, result, digit
var 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]

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()
}
[ View on GitHub | Edit on GitHub | Source on GitHub ]

How to use

You you can install via npm install locutus and require it via require('locutus/php/bc/bcround'). You could also require the bc module in full so that you could access bc.bcround instead.

If you intend to target the browser, you can then use a module bundler such as Browserify, webpack or rollup.js.

ES5/ES6

This function targets ES5, but as of Locutus 2.0.2 we also support ES6 functions. Locutus transpiles to ES5 before publishing to npm.

A community effort

Not unlike Wikipedia, Locutus is an ongoing community effort. Our philosophy follows The McDonald’s Theory. This means that we don't consider it to be a bad thing that many of our functions are first iterations, which may still have their fair share of issues. We hope that these flaws will inspire others to come up with better ideas.

This way of working also means that we don't offer any production guarantees, and recommend to use Locutus inspiration and learning purposes only.

Examples

Please note that these examples are distilled from test cases that automatically verify our functions still work correctly. This could explain some quirky ones.

#codeexpected result
1bcround(1, 2)'1.00'

« More PHP bc functions