最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to round a decimal to the nearest 0.5 (0.5, 1.5, 2.5, 3.5) - Stack Overflow

programmeradmin1浏览0评论

I want to round a number to the nearest 0.5. Not every factor of 0.5, just the 0.5s.

For example, 0.5, 1.5, 2.5, -1.5, -2.5. NOT 1, 1.5, 2, 2.5.

I'm confusing myself just explaining it, so here are some examples of expected outputs.

0.678 => 0.5
0.999 => 0.5
1.265 => 1.5
-2.74 => -2.5
-19.2 => -19.5

I have tried the following code with no luck,

let x = 1.296;
let y = Math.round(x);
let z = y + Math.sign(y) * .5; // 1.5 (Correct!)
let x = -2.6;
let y = Math.round(x);
let z = y + Math.sign(y) * .5; // -3.5 (WRONG, should be -2.5)

The code makes sense in my head, but dosen't work for negative numbers. What am I missing that would make this work?

I want to round a number to the nearest 0.5. Not every factor of 0.5, just the 0.5s.

For example, 0.5, 1.5, 2.5, -1.5, -2.5. NOT 1, 1.5, 2, 2.5.

I'm confusing myself just explaining it, so here are some examples of expected outputs.

0.678 => 0.5
0.999 => 0.5
1.265 => 1.5
-2.74 => -2.5
-19.2 => -19.5

I have tried the following code with no luck,

let x = 1.296;
let y = Math.round(x);
let z = y + Math.sign(y) * .5; // 1.5 (Correct!)
let x = -2.6;
let y = Math.round(x);
let z = y + Math.sign(y) * .5; // -3.5 (WRONG, should be -2.5)

The code makes sense in my head, but dosen't work for negative numbers. What am I missing that would make this work?

Share Improve this question asked Jan 12, 2021 at 4:24 Andrew LemonsAndrew Lemons 3421 gold badge3 silver badges7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

First, you can round to integer by

let x = 1.296;
let y = Math.round(x);

Then, you can subtract 0.5 first, then round, then add 0.5

let x = 1.296;
let y = Math.round(x-0.5);
let z = y + 0.5;

function getValue (a){
   var lowerNumber = Math.floor(a);
   console.log(lowerNumber +0.5);
}

getValue(0.678);
getValue(0.999);
getValue(1.265);
getValue(-2.74);
getValue(-19.2);

looks like you want lower full number + 0.5 ;

You can try this logic:

  • Get the decimal part from number.
  • Check if value is positive or negative. Based on this initialise a factor
    • For positive keep it 1
    • For negative keep it -1
  • Multiply 0.5 with factor and add it to decimal

var data = [ 0.678, -0.678, 0.999, 1.265, -2.74, -19.2 ]

const output = data.map((num) => {
  const decimal = parseInt(num)
  const factor = num < 0 ? -1 : 1;
  return decimal + (0.5 * factor)
})

console.log(output)

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论