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

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JavaScript: How can I split a decimal number into 2 part according to where the first zero occurs after a non-zero integer without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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.

Answer

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"
We are here to answer your question about JavaScript: How can I split a decimal number into 2 part according to where the first zero occurs after a non-zero integer - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji