0

I have a problem with decimal places. My code gives me the result 123 123 12, while I need to display the result in the form 12 312 312.

Can anyone help setting this formatting?

Code here:

        var fcqInteger = parseInt(fcq.replace(/\s/g, ''));
        valPrice = parseFloat(valPrice.replace(',', '.'));
        var marketCap = (fcqInteger * valPrice)+'';
        // result
        var marketCapParts = marketCap.match(/[\s\S]{1,3}/g) || []; 
        marketCap = marketCapParts.join(' '); 

Thanks for help.

6
  • What contains fcq and valPrice ? Commented Jan 17, 2020 at 10:27
  • A constant value that doesn't change. This is not an important variable. The most important is the variable is marketCap. Commented Jan 17, 2020 at 10:27
  • And valPrice ? Commented Jan 17, 2020 at 10:29
  • This is important to be able to reproduce Commented Jan 17, 2020 at 10:29
  • Another variable that gets the value from outside. It is formatted because it must format the result. Commented Jan 17, 2020 at 10:31

2 Answers 2

4

You could replace with space by looking to the end of the string for groupd of three.

var data = '12312312'

console.log(data.replace(/.{1,3}(?=(...)+$)/g, '$& '));  // replace
console.log(data.match(/.{1,3}(?=(...)*$)/g).join(' ')); // match/join

Sign up to request clarification or add additional context in comments.

5 Comments

It works, buy your code shortens my 8 character number to 5, so from 123 123 12 it gets 12 312. How to set this format for 8 characters?
this approach adds only spaces, but not shorten the string. please add some strings for testing to the question along with the wanted result.
i am using replace, your code has match and works different. by matching, the last portion goes. by using match, you need another quantifier for having an empty part, like /.{1,3}(?=(...)*$)/g
You helped me a lot. Thank you very much. Replacing +$ to *$ solved the problem.
1

You can use Number.toLocaleString and then replace the , with spaces.

let num = '123 123 12';
let out = Number(num.replace(/\s/g, '')).toLocaleString('us-US', {maximumFractionDigits: 5}).replace(/,/g, ' ');
console.log(out)

3 Comments

i guess you should specify locale string to toLocaleString, the above code, for instance, is not working for me.
To use the browser's default locale, omit this argument, so in my case ("it-IT") the separator is . not , var formatted = (fcqInteger * valPrice).toLocaleString('us-US').replace(/\./g," ")
@Nico added the locale thanks for pointing out, also updated to handle decimal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.