如何在c或c ++中的两位小数后舍入浮点数

时间:2018-04-21 06:45:59

标签: c++ c++11 floating-point rounding precision

如何在c或c ++中的两位小数后舍入浮点值

示例:

  1. 让输入为95.346789,因此输出为95.35

  2. 让输入95.345输出为95.35

  3. 让输入95.344输出为95.34

2 个答案:

答案 0 :(得分:-1)

在C:

<p-autoComplete name="student" [(ngModel)]="student" [ngModelOptions]="{standalone: true}" field="firstName" [forceSelection]="false" [suggestions]="filteredStudents"
   (completeMethod)="filterStudents($event)" [size]="30" [minLength]="1" placeholder="Hint: type 'v' or 'f'" [dropdown]="true">
   <ng-template let-student pTemplate="item">
     <div class="ui-helper-clearfix" style="border-bottom:1px solid #D5D5D5">
       <div style="font-size:18px;float:none;margin:10px 10px 0 0">{{student.firstName+' '+student.lastName}}</div>
     </div>
   </ng-template>
</p-autoComplete>

答案 1 :(得分:-2)

如下所示。希望它可以理解。 输出:https://www.ideone.com/EnP40j

#include <iostream>
#include <iomanip>
#include <cmath>

int main()
{
   float num1 = 95.345f;
   float num2 = 95.344f;

   num1 = roundf(num1 * 100) / 100; //rounding two decimals
   num2 = roundf(num2 * 100) / 100; //rounding two decimals

   std::cout << std::setprecision(2) << std::fixed
             << num1 << " " << num2 << std::endl;
   return 0;
}