3

I am working on a JS project and i have the following problem:

My input number goes from 0 to 10. (it can be 1, 2, 3.4, 5,9, etc..)

The expected output would be something out of 5 with only one lowered down decimal.

Examples:

9.7 / 10 would give 4.85 / 5 , the output has to be 4.8 (keep only one lowered down digit)

4.9 / 10 would give 2.45 / 5, the output has to be 2.4 (keep only one lowered down digit)

Thanks for your help.

Regards

  • 1
    This has been answered before at http://stackoverflow.com/questions/4912788/truncate-not-round-off-decimal-numbers-in-javascript – Vistari Feb 11 '16 at 11:24

5 Answers5

3

You can do this with a simple process:

  1. Multiply your number by 10.
  2. Floor it (using Math.floor).
  3. Divide it by 10.
Math.floor(4.85 * 10) / 10; // 4.8
Math.floor(2.45 * 10) / 10; // 2.4
Math.floor(3 * 10) / 10;    // 3

Taking 4.85 as an example:

  1. 4.85 * 10 equates to 48.5.
  2. Math.floor(48.5) equates to 48.
  3. 48 / 10 equates to 4.8.
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

try this

var x = 9.7; // input variable
var base = 10; //base like 10 in your case

var outof = 5; //rounded out of

Number(String((x/base)*outof).match(/^\d+(?:\.\d{0,1})?/)) //outputs one rounded off value for last digit;

last line will first compute the value which is

var value = (x/base)*outof;

then get only first digit after decimal

value = value.match(/^\d+(?:\.\d{0,1})?/);

convert the final value to a number

value = Number ( value );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Does this ugly to you?

Convert to string --> substring --> convert to number

var x = 9.47;
var x2 = (x+'').split(".");
x = parseFloat(x2[0]+"."+x2[1].substr(0,1));
Coisox
  • 1,002
  • 1
  • 10
  • 22
-1

You can use .toFixed()

For example

var N=2.45;

alert(N.toFixed(1));

will return 2.4

Hemal
  • 3,682
  • 1
  • 23
  • 54
-1
var x = 4.8555;
x = Math.floor(x * 100) / 100;
alert(x.toFixed(1));
suman das
  • 357
  • 1
  • 12
  • This does not work, it rounds to the higher decimal. –  Feb 11 '16 at 11:37
  • this will alert only 4.8 and you can run this one also sir – suman das Feb 11 '16 at 11:39
  • No, because 4.86 will return 4.9, the objective is to return 4.8 –  Feb 11 '16 at 11:42
  • Well, it does not work .. open your console and type var x = 4.98; x = Math.floor(x * 100) / 100; alert(x.toFixed(1)); it will return 5.0 instead of 4.9 –  Feb 11 '16 at 12:02