相关文章推荐
喝醉的骆驼  ·  Maven ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

You'll see in my form tag, I'm using toLocaleString to to put a separator in my final output. However I want a space instead of a comma. How can I achieve that?

Right now, the third output has a comma in it. But ideally I want all three outputs to have a space in it to make large numbers more readable.

Example: "5 000", "400 000" etc.

oninput="loanval.value=loan.value; periodval.value=period.value; paymentval.value=Math.floor(loan.value / period.value).toLocaleString()"> <label>Loan Amount</label> <input type="range" id="loan" name="loan" min="5000" max="400000" step="5000"> <output name="loanval" for="loan">0</output> <label>Loan Period</label> <input type="range" id="period" name="period" min="1" max="15"> <output name="periodval" for="period">0</output> <label>Your monthly repayment will be:</label> <output name="paymentval">0</output> </form>

The point of the .toLocaleString() function is that it chooses the correct thousands and decimal separators based on the locale (and lakh separators, etc), so there's no option to just explicitly say "I would like to use a space for this separator, please."

If you're absolutely certain your site will only be running in locales that use a period as the decimal separator you could just do .toLocaleString('en-US').replace(',', ' ')

That is, force it to use en-US which uses commas for thousands and periods for decimals, and then just manually replace the commas. It's not very elegant, but then I'd argue the whole idea of removing a locale's standard/recognizable thousands separator to make numbers "more readable" is itself not very elegant.

I don't think you'd want to use .replace(',', ' ') as that would only find the first instance. You could use the new .replaceAll(',', ' ') or regex to replace all instances murphworm Feb 12, 2022 at 7:54 console.log(num.toLocaleString('fr', { 'minimumFractionDigits': 2, 'maximumFractionDigits': 2
function addspace(num, separator) {
    var mainString = num.toString();
    mainString = mainString.split("").reverse().join("");
    mainString = mainString.match(/.{1,3}/g).join(separator);
    mainString = mainString.split("").reverse().join("");
    return mainString;
console.log(addspace(1000, " "));
console.log(addspace(10000, " "));

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question . Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers .