获取浮点数的第N个小数 [英] Getting the Nth Decimal of a Float

查看:130
本文介绍了获取浮点数的第N个小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用if语句在浮点数之间进行比较,但我不知道该怎么做。我搜索了很多,但没有得到答案。

I was trying to compare between decimals in floats using if statements, but I don't know how to do it. I searched a lot but didn't get the answer.

例如:

如果我有一个像5.26这样的浮点数,该如何说第二位小数(等于6)是否大于(小于)(某个数字)?!

If I have a float like this 5.26, how can I say if the 2nd decimal (which is 6) is bigger/smaller than (a certain number) or not?!

我希望清楚理解。

重新形成问题:

如果我的浮点数在小数点后有2个数字,我想检查 second 的数字是否大于 5(例如,例如)?

If I have a float that have 2 numbers after the decimal point, I want to check if the second number is bigger than "5" -for example- or not?

推荐答案

浮点数的第N个小数

以下是获取浮点数的第N个小数的技巧:

Here is a trick for getting the Nth decimal place of a float:


  • 取绝对值

  • 乘以10 n

  • int

  • 模量乘以10

  • Take the absolute value
  • Multiply by 10n
  • Cast to an int
  • Modulus by 10

示例

获取0.12438的第三位小数。我们希望答案是4。

Get the third decimal of 0.12438. We would expect the answer to be 4.


  • 0.12438


    • 取绝对值


    • 乘以10 < sup> 3

    • Multiply by 103

    • 发布到int


    • 模量增加10

    如何操作Works

    乘以10 n 会将您关心的小数点放在那个位置。转换为int会删除小数点。乘以10的模数会丢弃除那个位置以外的所有值。

    Multiplying by 10n gets the decimal you care about into the ones place. Casting to an int drops the decimals. Modulus by 10 drops all but the ones place.

    在输入为负的情况下,我们取绝对值。

    We take the absolute value in case the input is negative.

    代码段

    float num = 0.12438f;
    int thirdDecimal = (int)(Math.abs(num) * Math.pow(10,3)) % 10; // Equals 4
    int fifthDecimal = (int)(Math.abs(num) * Math.pow(10,4)) % 10; // Equals 3
    

    这篇关于获取浮点数的第N个小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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