PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 8, 2022

[FIXED] why does the number 51444.325061 doesnot round off to 51444.325 upto 3 decimal places? I want to round off this number in c programming

 August 08, 2022     c, decimal, floating-point, precision, rounding     No comments   

Issue

#include <stdio.h>
#include <stdlib.h>

int main() {
    float n;
    scanf("%f", &n);
    printf("%.3f", n);
}

input: 51444.325061

my output: 51444.324

expected output: 51444.325

why does I dont get the proper answer?


Solution

32-bit float can encode about 232 different values.

51444.325061is not one of them**. Instead the nearest float is exactly 51444.32421875. The next best choice would be 51444.328125.

Printing 51444.32421875 to 3 decimal places is best as "51444.324".


why does I dont get the proper answer?

float is too imprecise to encode 51444.325061 as OP desires. Using double will help. The same problem exists, yet only appears when about 16+ significant digits are needed.


** Encodable finite values are of the form: some_integer * 2some_exponent.



Answered By - chux - Reinstate Monica
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing