Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

changing the formatting of a number

New Here ,
Jun 03, 2010 Jun 03, 2010

hey,

working javascript CS4 with number with a lot of numbers behind the decimal isn't easy.

But i can't find anything how can change this...

ex: 12,248481545454 should be 12,25...

help...

TOPICS
Scripting
1.3K
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Valorous Hero , Jun 03, 2010 Jun 03, 2010

var number = 12.248481545454;
number.toFixed(2);

Translate
Valorous Hero ,
Jun 03, 2010 Jun 03, 2010

var number = 12.248481545454;
number.toFixed(2);

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Jun 03, 2010 Jun 03, 2010

var number = 12.248481545454;
number.toFixed(2);

Result of above code comes 12.24

But if you want 12.25 then use below code

var number = 12.248481545454;
alert(roundToDP (number ,2))

function roundToDP (val,dig)
{
     // Including all its zeros, lopping off beyond:
     val = Math.round(val*Math.pow(10,dig));
     // Force in decimal point at the right place:
     val = String(val);
   //  return val.slice(0,val.length-dig)+"."+val.slice(dig);
     return val.slice(0,val.length-dig)+"."+val.slice(val.length-dig);
}

Shonky

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
LEGEND ,
Jun 03, 2010 Jun 03, 2010
LATEST


WOW!

And I would have done:

var number = Math.round(12.248481545454*100)/100;

Or in function form:

var number = RoundWithDecimal(12.248481545454,2);

function RoundWithDecimal(number,decimals){
    var multiplier = Math.pow(10,decimals);
    return Math.round(number*multiplier)/multiplier;
}

Harbs

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines