Joji
Joji

Reputation: 5621

JavaScript: How can I split a decimal number into 2 part according to where the first zero occurs after a non-zero integer

Sorry if the title sounds confusing. Basically what I am trying to do is to split a decimal number like this 0.1000 into two part - 1. 0.1 and 000 so I can render them differently with different styles.

Check out this screenshot enter image description here

All the numbers are represented in strings. The tricky part is that we cannot split the number using number.split('0') since we only want to split at the first zero that appears after a non-zero integer.

Not sure how I can do this.

Upvotes: 1

Views: 269

Answers (5)

Aadesh Dhakal
Aadesh Dhakal

Reputation: 452

here is my answer. It uses split and substring to achieve what you want. Tried it in w3school's tryit editor. Handles all of your data in screenshot pretty well:

function myFunction() {
  var str = "0.01200";
  var partone = str.split(".")[0];
  var temp = str.split(".")[1];
  for (var i=0; i<temp.length; i++){
    if (temp[i] != 0 && temp[i+1] == 0){
        break;
    }
  }
  var parttwo = temp.substring(i+1);
  partone = partone + "." + temp.substring(0, i+1);
  var res = "partOne = " + partone + " and partTwo = " + parttwo;
  document.getElementById("demo").innerHTML = res;
}

Here is the screenshot: enter image description here

Upvotes: 0

a.mola
a.mola

Reputation: 4011

Here's my regex function

const number = ['0.1000', '2.534300', '1.2000', '1.004334000'];

function split_float(num) {
  const reg = /^(\d*\.\d*[^0])(0*)$/g;
  const [, ...matches] = [...num.matchAll(reg)][0];
  
  return matches;
}

console.log(number.map(split_float));

Upvotes: 0

ManuelMB
ManuelMB

Reputation: 1377

const number = 1.2345670089

let renderStyle1 = ''
let renderStyle2 = ''
 
const string = String(number) + '.'
const parts = string.split('.')
const decimals = parts[1]
const decimalsArray = Array.from(decimals);

// From MDN: The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
const firstIndexOfZero = decimalsArray.findIndex(x => x === '0'); 

// From MDN: The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified.

if(firstIndexOfZero === -1){
   renderStyle1 =  parts[0] + parts[1]
} else {
      renderStyle1 =  parts[0] + decimalsArray.slice(0, firstIndexOfZero).join('')  // using .join method to convert array to string without commas   
      renderStyle2 = decimalsArray.slice(firstIndexOfZero, decimalsArray.length).join('')  // using .join method to convert array to string without commas 
}

console.log(renderStyle1) // "1234567"
console.log(renderStyle2) // "0089"

Upvotes: 0

marks
marks

Reputation: 1391

If I did not misunderstand what you are trying to achieve, you can do it with a regex that only matches unlimited zeros that are at the end of the given string like follows:

function markNumber(num) {
    return num.replace( /(0{1,})$/g, '<span>$1</span>')
}

Upvotes: 2

Mr. Hedgehog
Mr. Hedgehog

Reputation: 2885

Messy, and, probably, can be improved, but this should work:

let re = /(\d*\.[1-9]*?)(0.*)/;
["1000", "1.01", "1.10", "1.000", "1.34043"].map((str) =>
  str.split(re).filter((entry) => entry !== "")
);

Upvotes: 0

Related Questions