Reputation:
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
Upvotes: 3
Views: 1853
Reputation: 1104
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));
Upvotes: 0
Reputation: 367
var x = 4.8555;
x = Math.floor(x * 100) / 100;
alert(x.toFixed(1));
Upvotes: -1
Reputation: 68393
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 );
Upvotes: 0
Reputation: 128791
You can do this with a simple process:
Math.floor
).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:
4.85 * 10
equates to 48.5
.Math.floor(48.5)
equates to 48
.48 / 10
equates to 4.8
.Upvotes: 3
Reputation: 3760
You can use .toFixed()
For example
var N=2.45;
alert(N.toFixed(1));
will return 2.4
Upvotes: -1