gpt4 book ai didi

ios - 获取小数点后一位 iOS Objective C

转载 作者:行者123 更新时间:2023-11-29 00:21:41 36 4
gpt4 key购买 nike

我正在尝试获取小数点后一位数并将其存储为 double 。例如:-

float A = 146.908295;
NSString * string = [NSString stringWithFormat:@"%0.01f",A]; // op 146.9
double B = [string doubleValue]; // op 146.900000

我想要 double 或浮点形式的输出为 146.9..,在复制或否决之前,请确保给出此输出的答案..谢谢

编辑:-

  NSString * str = [NSString stringWithFormat:@"%0.01f",currentAngle];

tempCurrentAngle = [str doubleValue];;

tempCurrentAngle = tempCurrentAngle - 135.0;

if (tempCurrentAngle == 8.7) {
NSLog(@"DONE ");
}

此处 currentAngle 来自 continueTrackingWithTouch 方法,该方法将以 float 形式存在。即使 tempCurrentAngle 值更改为 8.700000,它也不会进入 if 循环。

最佳答案

您可以比较字符串值而不是 double ,

 double currentAngle = 143.7;   // I have taken static values for demo. 
double tempCurrentAngle = 0.0;

NSString * str = [NSString stringWithFormat:@"%0.01f",currentAngle];

tempCurrentAngle = [str doubleValue];;

tempCurrentAngle = tempCurrentAngle - 135.0;

NSString *strToCompare = [NSString stringWithFormat:@"%0.01f",tempCurrentAngle];

if ([strToCompare isEqualToString:@"8.7"] ) {

NSLog(@"DONE ");
}

如果你逐行调试一次,你就会明白为什么它没有进入if caluse

tempCurrentAngle 得到 143.69999999999999 当你将 str 转换为 double 然后你减少 135.0 所以它的值将是 8.6999999999999886 然后你将它与 8.7 比较那么它肯定不相等!但如果您将 tempCurrentAngle 字符串转换为一位小数,那么它将是 8.7!所以你应该比较字符串值而不是 double 值!

关于ios - 获取小数点后一位 iOS Objective C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44065814/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com