Round-Off Decimal Number properly using Regular Expression🤔

Biswasindhu Mandal
3 min readJul 18, 2022

--

Photo by Mika Baumeister on Unsplash

We regularly used the decimal round-off function. Can we check if that follows the exact rounding-off rule?
I think we didn’t 😕, but we regularly used it.

👉 View Website

Let me show you some examples.

Round-Off in Python
Round-Off in Javascript
Round-Off in Java

There are 5 rules to round off any decimal number up to any decimal places. Generally round-off rules work properly if the next digit of the rounding digit is > or < 5. If the next digit of the rounding digit is 5 then trouble is coming. It’s not working according to the rules.

Resolved this issue using Regular Expression:

To resolve this issue basically, we need the round-off decimal digit, first discard digit after the round-off digit, and is there any other non-zero discard digit or not.
I am considering here to round off up to second decimal places

secondDD_regx = /(?<=[\d]*\.[\d]{1})[\d]/g; // roun-off digit
thirdDD_regx = /(?<=[\d]*\.[\d]{2})[\d]/g; // first discard digit
isNonZeroAfterThirdDD_regx = /(?<=[\d]*\.[\d]{3,})[1-9]/g;
isOddSecondDD_regx = /[13579]/g;

Now resolved it in Javascript:

const uptoOneDecimalPlaces_regx = /[\+\-\d]*\.[\d]{1}/g;
const secondDD_regx = /(?<=[\d]*\.[\d]{1})[\d]/g;
const thirdDD_regx = /(?<=[\d]*\.[\d]{2})[\d]/g;
const isNonZeroAfterThirdDD_regx = /(?<=[\d]*\.[\d]{3,})[1-9]/g;
const num = '5.285';const uptoOneDecimalPlaces = num.match(uptoOneDecimalPlaces_regx)?.[0];
const secondDD = num.match(secondDD_regx)?.[0];
const thirdDD = num.match(thirdDD_regx)?.[0];
const isNonZeroAfterThirdDD = num.match(isNonZeroAfterThirdDD_regx)?.[0];
const isOddSecondDD = /[13579]/g.test(secondDD);
// check carry
const carry = !thirdDD ? 0 : thirdDD > 5 ? 1 : thirdDD < 5 ? 0 : isNonZeroAfterThirdDD ? 1 : isOddSecondDD ? 1 : 0;
let roundOffValue;
if(/9/g.test(secondDD) && carry) {
roundOffValue = (Number(`${uptoOneDecimalPlaces}` + `${secondDD ? Number(secondDD) : 0}`) + Number(`0.0${carry}`)).toString();
} else {
roundOffValue = (uptoOneDecimalPlaces + ((secondDD ? Number(secondDD) : 0) + carry)).toString();
}
// Beaufity output : show exactly 2 decimal places if output is x.y or x
const dd = roundOffValue.match(/(?<=[\d]*[\.])[\d]*/g)?.toString().length;
roundOffValue = roundOffValue + (dd=== undefined ? '.00' : dd === 1 ? '0' : '');
console.log(roundOffValue);

For more details check GitHub code.

Learn Regular Expression: Puzzling with Regular Expression

--

--

Biswasindhu Mandal

I am a Software Engineer, living in Kolkata, India. I love to work as a Javascript, Node.js Full Stack developer and OTT Frontend Developer.