2

I have to round a number to 2 decimal places in javascript. But I also have to change the decimal separator from "." to ",".

I found out a few post on how to round the number to 2 decimal places

How to round1 How to round2

I found a few in hot to change the decimal separator

Change Decimal Separator1 Change Decimal Separator2

But they all manipulate the string, changing the "," for ".", or something like that. There is no direct way to set the decimal separator? Like a global configuration?

Community
  • 1
  • 1
Rafael Teles
  • 2,708
  • 2
  • 16
  • 32

1 Answers1

1

I recommend you to do this:

function decimalSeparator($yourInt){
 return parseInt( $yourInt ).toLocaleString()
}

EDIT Check this solution:

        function formatDK(num, decimals) {
            return formatLocale(num, decimals, '.', ',');
        } //for dk
        function formatUK(num, decimals) {
            return formatLocale(num, decimals, ',', '.');
        }  //for Uk 
        function formatLocale(num, decimals, kilosep, decimalsep) {
            var i, bNeg = num < 0, x = Math.round(num * Math.pow(10, decimals)), y = Math.abs(x).toString().split(''), z = y.length - decimals;

            if (z <= 0) {
                for (i = 0; i <= -z; i += 1) {
                    y.unshift('0');
                }
                z = 1;
            }
            if (decimals > 0) {
                y.splice(z, 0, decimalsep);
            }
            while (z > 3) {
                z -= 3;
                y.splice(z, 0, kilosep);
            }
            if (bNeg) {
                y.splice(0, 0, '-');
            }
            return y.join('');
        }

There is no global config for this, you will have to use this method, i recommend you to define this and use it in all places, that its what i do.

cesar moro
  • 168
  • 8
  • Well, I didn't get the idea =/. With that function I'll only get the "integer" value of the number. Or did I understand it wrong? – Rafael Teles Aug 18 '15 at 13:54
  • change parseInt for parseFloat($yourInt).toLocaleString().toFixed(2) //this is to get 2 decimals – cesar moro Aug 18 '15 at 19:16
  • If I do so, I will have the number with 2 decimals, but I'll still have the "." instenad of "," problem – Rafael Teles Aug 18 '15 at 20:07
  • Rafael the . is becouse of the locale of your computer, people with another locale on his browser must see this correctly, but try my edit upside – cesar moro Aug 19 '15 at 13:08