0

what i want is just to show the result of a variable with just one number after the ".". i've tried toFixed and toPrecision but they round the whole number, and i want the result to be exact in:

var result = 6.853571428571428; //
$("#id").html(result); //want to show 6.8

i want to show just the "6.8", using functions like toFixed(2) and toPrecision(2) gives me 6.9. also tried Math.round(number * 10) / 10 but with the same results

kleb_
  • 1
  • 1
  • 2
    Does this answer your question? [Truncate number to two decimal places without rounding](https://stackoverflow.com/questions/4187146/truncate-number-to-two-decimal-places-without-rounding) – Pan Vi Jun 25 '21 at 05:29
  • i've tried that, even in the example, they are rounding 15.7784514 to 17.8, i'd like to get just the 1st number after ".", in the example you gave me should be 17.7 instead if 17.8 :) – kleb_ Jun 25 '21 at 05:34
  • just slightly adjust the regex in the answer `var with1Decimals = num.toString().match(/^-?\d+(?:\.\d{0,1})?/)[0]` https://jsfiddle.net/xeqfb2vd/ – Pan Vi Jun 25 '21 at 05:40

2 Answers2

1
var result = 6.853571428571428;
$("#id").html(Math.trunc(result*10)/10);
guolei1998
  • 27
  • 2
  • This is alot prettier than my eyesore! `$("#id").html((+((""+(result*10)).split('.')[0])/10))` - thanks for sharing. i didn't know about `Math.trunc` – Kinglish Jun 25 '21 at 05:37
0

check other and complete solutions here

    var result = 6.853571428571428; 
    result = result.toString(); //pars it to String 
    result = result.slice(0, (result.indexOf("."))+2);
    console.log(Number(result));
Amir Danish
  • 418
  • 5
  • 8