如何舍入到最接近的50或100? [英] how to round to nearest 50 or 100?

查看:147
本文介绍了如何舍入到最接近的50或100?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有数字(十进制)我想将它舍入到最接近的50:


  1. 122 => round to 150

  2. 177 =>轮到200
  3. 157 =>轮到200
  4. 57 =>轮到100 ;

  5. 37 =>轮到50;
  6. 1557 =>轮到1600
  7. 3537 =>轮到3550

如何用java / groovy做到这一点?

解决方案

Groovy x + (50 - (x%50?:50))

  def round50up = {int x - > 
x +(50 - (x%50?:50))
}

assert round50up(122)== 150
assert round50up(177)== 200
assert round50up(157)== 200
assert round50up(57)== 100
assert round50up(37)== 50
assert round50up(1557)== 1600
assert round50up(3537)== 3550
assert round50up(100)== 100
assert round50up(200)== 200
assert round50up(250)== 250

测试 此处


I have numbers (in decimal) I want to round it to "nearest 50":

  1. 122 => round to 150
  2. 177 => round to 200
  3. 157 => round to 200
  4. 57 => round to 100;
  5. 37 => round to 50;
  6. 1557 => round to 1600
  7. 3537 => round to 3550

how to do that with java/groovy ?

解决方案

Groovy x + (50 - (x % 50 ?: 50)) :

def round50up = { int x ->
    x + ( 50 - ( x % 50 ?: 50 ) )
}

assert round50up( 122  ) == 150 
assert round50up( 177  ) == 200 
assert round50up( 157  ) == 200 
assert round50up( 57   ) == 100 
assert round50up( 37   ) == 50 
assert round50up( 1557 ) == 1600 
assert round50up( 3537 ) == 3550 
assert round50up( 100  ) == 100 
assert round50up( 200  ) == 200 
assert round50up( 250  ) == 250

Test it here.

这篇关于如何舍入到最接近的50或100?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆